如何通过光标拖动来阻止文本/元素选择


81

我做了一个分页控件,我注意到在单击按钮时很容易意外地选择单个图像和文本。有可能防止这种情况吗?

为了澄清选择,我的意思是用鼠标突出显示。(尝试将鼠标从屏幕的一侧拖到另一侧。)

如果尝试突出显示此网格中的文本/控件,则无法选择它。怎么做? 链接



Answers:


108

拖动并选择在鼠标按下事件时初始化,并在随后的鼠标移动时更新。处理事件以开始拖动或跟随鼠标时,请取消事件的冒泡并覆盖默认的浏览器返回:

在您开始拖动鼠标并移动处理程序时,就像这样:

e=e || window.event;
pauseEvent(e);
function pauseEvent(e){
    if(e.stopPropagation) e.stopPropagation();
    if(e.preventDefault) e.preventDefault();
    e.cancelBubble=true;
    e.returnValue=false;
    return false;
}

11
是的,e.preventDefault()应该是现代浏览器中所需要的。其余代码是多余的:window.event适用于IE的较早版本,但是由于这些事件不具有preventDefault方法,并且在pauseEvent函数调用时不会返回return false,所以它什么也不做。 (甚至在2011年也没有)。
Sjeiti 2015年

17
CSS:这user-select: none;是我用的。我应该再考虑
不用

50

对于拖动,您正在捕获mousedownmousemove事件。(希望touchstart也包括touchmove事件,以支持触摸界面。)

你需要调用event.preventDefault()在双方downmove事件,以保持浏览器选择文本。

例如(使用jQuery):

var mouseDown = false;
$(element).on('mousedown touchstart', function(event) {
  event.preventDefault();
  mouseDown = true;
});
$(element).on('mousemove touchmove', function(event) {
  event.preventDefault();
  if(mouseDown) {
    // Do something here.
  }
});
$(window.document).on('mouseup touchend', function(event) {
  // Capture this event anywhere in the document, since the mouse may leave our element while mouse is down and then the 'up' event will not fire within the element.
  mouseDown = false;
});

感谢Robin,出于好奇,window.documentandwindow或just之间有区别document吗?我很确定documentwindow..的孩子
松饼人

1
window是Javascript在浏览器中运行的最外部范围。因此,任何未在函数内部声明的变量都是的属性windowdocument直接引用实际上是指window.document
罗宾·多尔蒂

3
据我所知,仅在“ mousedown”事件上取消默认值就足够了。
tremby

23

这是一个很旧的帖子。它可能无法完全回答这种情况,但是我将CSS用于解决方案:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

这正是我所需要的
Luc-Olsthoorn

19

我想发表评论,但是我没有足够的声誉。使用@kennebec的建议功能解决了我的JavaScript拖动库中的问题。它完美无瑕。

function pauseEvent(e){
    if(e.stopPropagation) e.stopPropagation();
    if(e.preventDefault) e.preventDefault();
    e.cancelBubble=true;
    e.returnValue=false;
    return false;
}

在我识别出我单击了正确的元素后,立即在mousedown和mousemove自定义函数中调用了它。如果我只是在函数顶部调用它,我将杀死文档上的任何单击。我的功能被注册为document.body中的事件。


2
您现在还有10个:)
Adaptabi



0

只需按以下方式选择调用blur()函数来防止它:

 <input Value="test" onSelect="blur();">

0

如果您需要使用JavaScript阻止某个元素的文本选择,那么对我而言,最简单的方法是分配userSelect样式,如下所示:

var myElement = document.createElement('div');
myElement.style.userSelect = 'none';
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.