javascript 防止鼠标拖动时选择文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29908261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prevent text selection on mouse drag
提问by RandomClown
How can I prevent text selection withoutusing the traditional method e.stopPropagation
(related question at bottom)?
Is there a call I can make to say "unhighlight whatever is highlighted"?
如何在不使用传统方法的情况下防止文本选择e.stopPropagation
(底部的相关问题)?
是否可以打电话说“取消突出显示的任何内容”?
I bound mouse events on the document because there are about a hundred [more or less] elements in the page that I want to have interact with each other.
我在文档上绑定了鼠标事件,因为页面中有大约一百个 [或多或少] 元素我希望彼此交互。
The reason I don't bind events to the elements instead is because when the mouse moves off the element, all mouse events stop triggering. I need to bind to the document to correctly watch mouse events.
我不将事件绑定到元素的原因是因为当鼠标移离元素时,所有鼠标事件都会停止触发。我需要绑定到文档才能正确观看鼠标事件。
The problem with using the method traditional method (link below) is that by the time the listener is triggered, the elements with text has already evaluated the mouse event.
使用传统方法(下面的链接)的问题在于,在触发侦听器时,带有文本的元素已经评估了鼠标事件。
My code works fine for Chrome. The issues below applies to Firefox.
我的代码适用于 Chrome。以下问题适用于 Firefox。
Related Question:How can I prevent text/element selection with cursor drag
This talks about preventing bubbling to the text element with:
相关问题:如何通过光标拖动防止文本/元素选择
这谈到防止冒泡到文本元素:
if(e.stopPropagation) e.stopPropagation();
if(e.preventDefault) e.preventDefault();
e.cancelBubble=true;
e.returnValue=false;
return false;
回答by iamjpg
Apologies for deleting my last answer but I realized it still wouldn't work in FF.
抱歉删除我的最后一个答案,但我意识到它在 FF 中仍然不起作用。
I believe that this answer, along with the CSS answer above, will produce the result you're looking for. Here is a solution that works cross-browser.
我相信这个答案,连同上面的 CSS 答案,会产生你正在寻找的结果。这是一个跨浏览器的解决方案。
var unFocus = function () {
if (document.selection) {
document.selection.empty()
} else {
window.getSelection().removeAllRanges()
}
}
called onmouseup
and onmousemove
does the trick.
调用onmouseup
并解决onmousemove
问题。
Here's the fiddle: http://jsfiddle.net/z2kpcwb6/
这是小提琴:http: //jsfiddle.net/z2kpcwb6/
回答by spintron
you can disable selection on the element using css.
您可以使用 css 禁用对元素的选择。
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}