How to stop the user from highlighting any text using javascript?

This question already has an answer here:

  • How to disable text selection highlighting? 37 answers

  • Yes, you can listen for the onselectstart event and cancel it. Here's an example.


    Try this out

    function disableSelection(target){
        if (typeof target.onselectstart!="undefined") // IE
            target.onselectstart=function(){return false;};
        else if (typeof target.style.MozUserSelect!="undefined") // Firefox
            target.style.MozUserSelect="none";
        else // Opera and the others
            target.onmousedown=function(){return false;};
        target.style.cursor = "default";
    }
    

    Usage :

    disableSelection(document.body);
    

    Working jsBin


    我知道你想要一个JS解决方案,但这种CSS风格应该适用于所有主要浏览器:

    .nohighlight{
        -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/7132.html

    上一篇: 如何避免这与CSS?

    下一篇: 如何阻止用户使用JavaScript突出显示任何文本?