原生javascript禁用和屏蔽鼠标右键

 1 (function(){
 2     var doc=document,
 3         ua = navigator.userAgent.toLowerCase(),
 4         check = function(r){return r.test(ua);},
 5         isOpera = check(/opera/),
 6         isChrome = check(/chrome/),
 7         isWebKit = check(/webkit/),
 8         isSafari = !isChrome && check(/safari/),
 9         isSafari2 = isSafari && check(/applewebkit\/4/),
10         isSafari3 = isSafari && check(/version\/3/),
11         isSafari4 = isSafari && check(/version\/4/),
12         isIE = !isOpera && check(/msie/),
13         isIE7 = isIE && check(/msie 7/),
14         isIE8 = isIE && check(/msie 8/),
15         isIE9 = isIE && check(/msie 9/),
16         isIE10 = isIE && check(/msie 10/),
17         isIE11 = isIE && check(/msie 11/),
18         isIE6 = isIE && !isIE7 && !isIE8 && !isIE9 && !isIE10 && !isIE11,
19         isGecko = !isWebKit && check(/gecko/),
20         isGecko2 = isGecko && check(/rv:1\.8/),
21         isGecko3 = isGecko && check(/rv:1\.9/);
22     function preventKey(e) {
23         var ev = e || window.event,//获取event对象  
24         obj = ev.target || ev.srcElement,//获取事件源  
25         t = obj.type || obj.getAttribute('type'),readonly = obj.readOnly||obj.getAttribute('readonly'), code = ev.keyCode||ev.which||ev.charCode,charcode = String.fromCharCode(code).toLowerCase();//获取事件源控件类型,控件只读属性,键盘值
26         if ( (code == 8 && t != "password" && t != "text" && t != "textarea")||(readonly&&(t == "password" || t == "text" || t == "textarea"))) {//除不只读输入框外禁止后退键
27             return false;
28         }
29         if (((isOpera || isGecko)?ev.which==0:true)&&(code == 116 || code == 122|| code == 123 || (ev.shiftKey && code == 121))||(((isOpera || isGecko)?ev.which!=0:true)&&ev.ctrlKey && (charcode == 'a' || charcode == 's'))) {//屏蔽 F5,F11,F12,shift+F10,ctrl+a,ctrl+s
30             if (isIE)
31                 ev.keyCode = 0;
32             ev.returnValue = false;
33             return false;
34         }
35     };
36     if (isOpera || isGecko)
37         doc.onkeypress = preventKey;
38     else if (isIE || isChrome || isSafari)
39         doc.onkeydown = preventKey;
40     if(isIE)document.onselectstart=function(){return false;};
41     doc.oncontextmenu = function(){
42         if(window.event){
43             window.event.cancelBubble = true;
44             window.event.returnValue=false;
45         }
46         return false;
47     };
48     try{window.history.forward(1);}catch(e){}
49 })();

 

posted @ 2018-01-03 14:47  王默默  阅读(658)  评论(0编辑  收藏  举报