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

这个问题在这里已经有了答案:

  • 如何禁用文本选择突出显示? 37个答案

  • 在大多数浏览器中,这可以使用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;
    }
    

    对于IE <10和Opera,您将需要使用unselectable您希望是不可选择的元素的属性。 您可以使用HTML中的属性来设置它:

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

    可悲的是,这个属性没有被继承,这意味着你必须在<div>的每个元素的开始标签中放置一个属性。 如果这是一个问题,您可以改用JavaScript来为元素的后代递归执行此操作:

    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>
    

    编辑

    代码显然来自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/7109.html

    上一篇: Is there a way to make text unselectable on an HTML page?

    下一篇: Prevent selection of text outside a scrolling element on Firefox