how to block text selection without input textarea

2019-02-11 01:51发布

问题:

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 omitformtags=["input", "textarea", "select"]
 omitformtags=omitformtags.join("|")
 function disableselect(e){
  if (omitformtags.indexOf(e.target.tagName.toLowerCase())==-1)
   return false
  }
 function reEnable(){
   return true
  }

 if (typeof document.onselectstart!="undefined")
  document.onselectstart=new Function ("return false")
 else{
  document.onmousedown=disableselect
  document.onmouseup=reEnable
 }
  document.onmousedown=click;
  function click()
 {
  if ((event.button==2) || (event.button==3)) { alert("Yazı Kopyalayamazsınız!");}

 }

i need to work it the same way in other browsers, there must be a ready script, just couldnt find in net..

回答1:

<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.



回答2:

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..)