防止HTML中的选择

WhitewallTower提出了一个问题:Prevent selection in HTML,或许与您遇到的问题类似。

回答者Tim Down给出了该问题的处理方式:

The proprietary variations of user-selectwill work in most modern browsers:

*.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in IE 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}

For IE < 10 and Opera, you will need to use the unselectableattribute of the element you wish to be unselectable. You can set this using an attribute in HTML:

<div id="foo" unselectable="on" class="unselectable">...</div>

Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <div>. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:

function makeUnselectable(node) {
    if (node.nodeType == 1) {
        node.setAttribute("unselectable", "on");
    }
    var child = node.firstChild;
    while (child) {
        makeUnselectable(child);
        child = child.nextSibling;
    }
}

makeUnselectable(document.getElementById("foo"));

希望本文对你有帮助,欢迎支持JavaScript中文网

原文链接:stackoverflow.com

上一篇:动态加载CSS样式表不在IE工作;
下一篇:像Python这样的JavaScript有字典吗?

相关推荐

官方社区

扫码加入 JavaScript 社区