禁用HTML元素上的拖放?

问题描述 投票:91回答:8

我正在开发一个Web应用程序,我正在尝试实现一个功能齐全的窗口系统。现在它进展顺利,我只遇到一个小问题。有时当我去拖动我的应用程序的一部分(通常是我的窗口的角落div,它应该触发调整大小操作)时,Web浏览器变得聪明并认为我的意思是拖放一些东西。最终结果,我的操作被搁置,而浏览器执行拖放操作。

是否有一种简单的方法来禁用浏览器的拖放?理想情况下,我希望能够在用户点击某些元素时关闭它,但重新启用它,以便用户仍然可以在我的窗口内容上使用浏览器的常规功能。我正在使用jQuery,虽然我无法找到它浏览文档,但如果你知道一个纯粹的jQuery解决方案,那就太棒了。

简而言之:我需要在用户按下鼠标按钮时禁用浏览器文本选择和拖放功能,并在用户释放鼠标时恢复该功能。

javascript jquery css webbrowser-control
8个回答
68
投票

尝试阻止mousedown事件的默认值:

<div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false">asd</div>

要么

<div onmousedown="return false">asd</div>

195
投票

这件事有效.....试试吧。

<BODY ondragstart="return false;" ondrop="return false;">

希望能帮助到你。谢谢


15
投票

您只需使用draggable="false"属性即可禁用拖动。 http://www.w3schools.com/tags/att_global_draggable.asp


13
投票

这可能有效:您可以禁用css3选择文本,图像和基本上所有内容。

.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in IE 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}

当然只适用于较新的浏览器。有关详细信息,请检查

How to disable text selection highlighting using CSS?


7
投票

使用jQuery,它将是这样的:

$(document).ready(function() {
  $('#yourDiv').on('mousedown', function(e) {
      e.preventDefault();
  });
});

在我的情况下,我想从输入中的drop text禁用用户,所以我使用“drop”而不是“mousedown”。

$(document).ready(function() {
  $('input').on('drop', function(event) {
    event.preventDefault();
  });
});

相反,event.preventDefault()可以返回false。 Here's the difference.

和代码:

$(document).ready(function() {
  $('input').on('drop', function() {
    return false;
  });
});

0
投票

尝试这个

$('#id').on('mousedown', function(event){
    event.preventDefault();
}

0
投票

对于input元素,this answer适合我。

我在Angular 4中的自定义输入组件上实现了它,但我认为它可以用纯JS实现。

HTML

<input type="text" [(ngModel)]="value" (ondragenter)="disableEvent($event)" 
(dragover)="disableEvent($event)" (ondrop)="disableEvent($event)"/>

组件定义(JS):

export class CustomInputComponent { 

  //component construction and attribute definitions

  disableEvent(event) {
    event.preventDefault();
    return false;
  }
}

0
投票

使用@ SyntaxError的答案,https://stackoverflow.com/a/13745199/5134043

我已经设法在React中做到了这一点;我能弄清楚的唯一方法是将ondragstart和ondrop方法附加到ref,如下所示:

  const panelManagerBody = React.createRef<HTMLDivElement>();
  useEffect(() => {
    if (panelManagerBody.current) {
      panelManagerBody.current.ondragstart = () => false;
      panelManagerBody.current.ondrop = () => false;
    }
  }, [panelManagerBody]);

  return (
    <div ref={panelManagerBody}>

-1
投票

这个JQuery为我工作: -

$(document).ready(function() {
  $('#con_image').on('mousedown', function(e) {
      e.preventDefault();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.