article:
tag:
mod code publish @2011-06-28

CSS > CSS rule to disable text selection highlighting 上一篇 | 下一篇

js, css, html, selection, drag, select, text

In most browsers, this can be achieved using proprietary variations on the proposed-but-now-defunct CSS3 user-select property:

*.unselectable {
   -moz-user-select: 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 unselectable attribute 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"));

Update 30 April 2014: This tree traversal needs to be re-run whenever a new element is added to the tree, but it seems from a comment by @Han that it is possible to avoid this by adding a mousedownevent handler that sets unselectable on the target of the event. See http://jsbin.com/yagekiji/1 for details.


This still doesn't cover all possibilities. While it is impossible to initiate selections in unselectable elements, in some browsers (IE and Firefox, for example) it's still impossible to prevent selections that start before and end after the unselectable element without making the whole document unselectable.

 

http://stackoverflow.com/questions/826782/css-rule-to-disable-text-selection-highlighting/4358620#4358620

 

@suches
http://btbtd.com/mods/code/item.php?uid=1&item=4800

发表于 @ 2014-05-07 00:44:25

该文章暂时没有回复
评论内容:
昵称:
验证码: