JS實現禁止鼠標右鍵的功能


遇到網頁上有精美圖片或者精彩文字想保存時,通常大家都是選中目標后按鼠標右鍵,在彈出菜單中選擇“圖片另存為”或“復制”來達到我們的目的。但是,目前有許多網頁都屏蔽了鼠標右鍵,那么用js如何實現禁止鼠標右鍵的功能呢?

1.與禁止鼠標右鍵相關的JS說明

  1. <script type="text/javascript">
  2. document.oncontextmenu=new Function("event.returnValue=false;");
  3. document.onselectstart=new Function("event.returnValue=false;");
  4. </script>

2.禁止鼠標右鍵火狐失靈

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>禁止鼠標右鍵</title>
  5. <meta charset="utf-8">
  6. </head>
  7. <body>
  8. <div class="poo">這個頁面不能使用鼠標右鍵</div>
  9. <!-- 禁止鼠標右鍵 -->
  10. <script type="text/javascript">
  11. if (window.Event){
  12. document.captureEvents(Event.MOUSEUP);
  13. }
  14. function nocontextmenu(){
  15. event.cancelBubble = true
  16. event.returnValue = false;
  17. return false;
  18. }
  19. function norightclick(e) {
  20. if (window.Event) {
  21. if (e.which == 2 || e.which == 3)
  22. return false;
  23. } else if (event.button == 2 || event.button == 3){
  24. event.cancelBubble = true
  25. event.returnValue = false;
  26. return false;
  27. }
  28. }
  29. document.oncontextmenu = nocontextmenu; // for IE5+
  30. document.onmousedown = norightclick; // for all others
  31. </script>
  32. </body>
  33. </html>

3.禁止選擇文本

  1. <script type="text/javascript">
  2. var omitformtags=["input", "textarea", "select"];
  3. omitformtagsomitformtags=omitformtags.join("|");
  4. function disableselect(e){
  5. if (omitformtags.indexOf(e.target.tagName.toLowerCase())==-1){
  6. return false;
  7. }
  8. }
  9. function reEnable(){
  10. return true;
  11. }
  12. if (typeof document.onselectstart!="undefined"){
  13. document.onselectstart=new Function ("return false");
  14. }else{
  15. document.onmousedown=disableselect;
  16. document.onmouseup=reEnable;
  17. }
  18. </script>

4.屏蔽ctrl按鍵

  1. document.onkeydown=function(){
  2. if(event.ctrlKey)return false;
  3. }

以上所述是小編給大家介紹的JS實現禁止鼠標右鍵的功能,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM