JavaScript 不可选择的文本在 Chrome/Internet Explorer 中不起作用

标签 javascript text jquery-ui-selectable

在 Firefox 中似乎很好,Chrome 和 Internet Explorer 中的文本仍然可以选择,有什么办法可以解决这个问题吗?该代码取自另一个问题(我现在找不到),所以它可能已过时?

// Prevent selection
function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") // Internet Explorer route
        target.onselectstart = function() { return false }
    else if (typeof target.style.MozUserSelect != "undefined") // Firefox route
        target.style.MozUserSelect = "none"
    else // All other routes (for example, Opera)
        target.onmousedown = function() { return false }
}

在代码中用作:

disableSelection(document.getElementById("gBar"));

最佳答案

对于 webkit 使用 khtmlUserSelect 而不是 MozUserSelect

在 Opera 和 MSIE 中,您可以将 unselectable-property 设置为“On”

由于gecko/webkit相关的样式都是CSS,所以可以用一个类来套用:

<script type="text/javascript">
<!--
function disableSelection(target)
{
  target.className='unselectable';
  target.setAttribute('unselectable','on');
}
//-->
</script>
<style type="text/css">
<!--
.unselectable{
-moz-user-select:none;
-khtml-user-select: none;
}
-->
</style>

注意:unselectable 不会传递子元素,因此如果 target 中除了 textNodes 之外还有其他任何东西,则需要使用 MSIE/opera 已有的解决方法。

关于JavaScript 不可选择的文本在 Chrome/Internet Explorer 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4312413/

相关文章:

javascript - 按字符串拆分仅适用于第一个子字符串

java - 将文件名与 id 进行匹配

jquery - 如何从 checkin 和 checkout <li> 中获取值(value)?

Javascript 用值填充键值是一个数组

javascript - 在对象构造函数中使用对象字面量符号的好处?

javascript - 替换为 Javascript 中的正则表达式

java - 在 JAVA 中将数据写入 .txt 文件?

Java - 无法添加文本

javascript - 如何在不折叠的情况下将div绘制到特定位置已经存在的div或没有覆盖