如何阻止在Google Chrome中选择文字?

Fra*_*urd 18 javascript

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

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

function disableSelection() {
   document.onselectstart = function() {return false;} // ie
   document.onmousedown = function() {return false;} // others
}
function enableSelection() {
   document.onselectstart = null; // ie
   document.onmousedown = null; // others
}
Run Code Online (Sandbox Code Playgroud)

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

Lir*_*una 45

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

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

.no-select
{
   user-select: none;
   -o-user-select:none;
   -moz-user-select: none;
   -khtml-user-select: none;
   -webkit-user-select: none;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 抨击IE是如此2001年. (20认同)
  • IE不被视为网络浏览器?怎么样? (9认同)
  • 在stackoverflow的问题数据库中搜索,看看有多少'在Firefox上运行,在IE上不起作用'你可以找到问题:) (7认同)
  • IE为答案+1,IE为+1.呸,我们只能给一个+1 :)抨击IE总是`Time.now`只要它可用. (7认同)
  • 对于那些在需要IE的地方工作的人来说,IE10使用`-ms-user-select`增加了对此的支持 (2认同)

Tim*_*own 19

要使用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
Run Code Online (Sandbox Code Playgroud)

请注意,对于IE和Opera,该unselectable属性不会被元素的子元素继承,因此el还需要将所有子元素都unselectable设置为"on".