在 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/