Is there a way to make text unselectable on an HTML page?

This question already has an answer here:

  • How to disable text selection highlighting? 37 answers

  • In most browsers, this can be achieved using CSS:

    *.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 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"));
    

    <script type="text/javascript">
    
    /***********************************************
    * Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
    * This notice MUST stay intact for legal use
    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
    
    ***********************************************/
    
    
    function disableSelection(target){
    
        if (typeof target.onselectstart!="undefined") //IE route
            target.onselectstart=function(){return false}
    
        else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
            target.style.MozUserSelect="none"
    
        else //All other route (ie: Opera)
            target.onmousedown=function(){return false}
    
        target.style.cursor = "default"
    }
    
    
    
    //Sample usages
    //disableSelection(document.body) //Disable text selection on entire body
    //disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"
    
    
    </script>
    

    EDIT

    Code apparently comes from http://www.dynamicdrive.com


    所有正确的CSS变体是:

    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    
    链接地址: http://www.djcxy.com/p/7110.html

    上一篇: 如何使HTML文本无法选择

    下一篇: 有没有办法让文本在HTML页面上无法选择?