how to block text selection without input textarea and select items

后端 未结 2 765
忘掉有多难
忘掉有多难 2021-01-03 09:37

How to block text selection without input textarea and select items i actually have the script that works in IE but not in other browsers, here it is:

 var o         


        
相关标签:
2条回答
  • 2021-01-03 10:21
    <div onmousedown='return false;' onselectstart='return false;'></div>
    

    onmousedown disables the selection for Firefox, Safari, Opera, Chrome and most other web browsers, onselectstart for IE.

    Though disabling text selection and context menus is very bad style and does not prevent the pro-users from selecting your text. Simply disabling JavaScript in their browsers enables the selection again.

    0 讨论(0)
  • 2021-01-03 10:21

    Updated my answer to be more clear:

    browsers can disable selecting using css styles or using special element attribute. This way is better:

    • no script to support
    • no fear that user disables script and copies content she needs
    • elegant solution

    Opera and IE ignores such a style, but there is html element attribute unselectable, which denies selecting. Try the following page (I tested in IE8, FF3.6, Safari5, opera11, Chrome8):

    <html>
    
    <head>
    
    <style>
    
    .unselectable {
        -moz-user-select: none; /* for FireFox */
        -webkit-user-select: none; /* for Chrome and Safari */
        -khtml-user-select: none; /* probably old webkit browsers, but new support it too */
        user-select: none; /* for future CSS3 compliant browsers */
    }
    
    </style>
    
    </head>
    
    <body>
    
    <!-- add unselectable class to deny selecting in FF, Chrome, Safari and CSS3 compliant browsers -->
    <!-- add unselectable attribute to deny selecting in Opera and IE -->
    <div class="unselectable" unselectable="on">test</div>
    
    </body>
    
    </html>
    

    For additional information about it visit this page. Now you can pick best option for you to use/mantain. One more time - this solution does not need javascript at all and should be imho more safe (if you can edit html\css pages and don't need dynamic. otherwise you can try to add css class\element attribute through javascript..)

    0 讨论(0)
提交回复
热议问题