Javascript 如何防止在 Google Chrome 中选择文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2212542/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:15:29  来源:igfitidea点击:

How can I prevent selecting text in Google Chrome?

javascript

提问by Frank Furd

Doesn't oEvent.preventDefault(); work in GC? I need to prevent selecting text when the onmove event is triggered.

不oEvent.preventDefault(); 在GC工作?我需要在触发 onmove 事件时阻止选择文本。

EDIT:It turns out to be very easy...

编辑:事实证明这很容易......

function disableSelection() {
   document.onselectstart = function() {return false;} // ie
   document.onmousedown = function() {return false;} // others
}
function enableSelection() {
   document.onselectstart = null; // ie
   document.onmousedown = null; // others
}

After that, there's no text selection triggered on the move event (ie. on the select event -- ie - indeed ie!)

在那之后,没有在移动事件上触发文本选择(即在选择事件上——即——确实是!)

回答by LiraNuna

-webkit-user-select: noneCSS style controls whether the user is allowed to select the
text of the element.

-webkit-user-select: noneCSS 样式控制是否允许用户选择
元素的文本。

For completeness sake, this covers all supporting browsers (IE is not considered a web browser):

为了完整起见,这涵盖了所有支持的浏览器(IE 不被视为网络浏览器):

.no-select
{
   user-select: none;
   -o-user-select:none;
   -moz-user-select: none;
   -khtml-user-select: none;
   -webkit-user-select: none;
}

To do it through Javascript, just create a class and add the node's attributes.

要通过 Javascript 完成,只需创建一个类并添加节点的属性。

回答by Tim Down

To do it using JavaScript:

要使用 JavaScript 做到这一点:

var el = document.getElementById("myElement"), s = el.style;
s.userSelect = "none";
s.webkitUserSelect = "none";
s.MozUserSelect = "none";
el.setAttribute("unselectable", "on"); // For IE and Opera

Note that for IE and Opera, the unselectableattribute isn't inherited by an element's children, so any child elements of elwill also need unselectableto be set to "on".

请注意,对于 IE 和 Opera,该unselectable属性不会被元素的子元素继承,因此 的任何子元素el也需要unselectable设置为"on"