禁止鼠标右键菜单,自己制作右键菜单
JS代码:
View Code
1 <script> 2 function getPosition(ev) //获取页面到鼠标点的X Y坐标 3 { 4 var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; 5 var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft; 6 return{x: scrollLeft+ev.clientX,y: scrollTop+ev.clientY}; 7 }; 8 9 document.oncontextmenu=function(ev) //oncontextmenu=鼠标右键 10 { 11 var oUl=document.getElementById('ul'); 12 var oEvent=ev||event; 13 var pos=getPosition(oEvent); 14 oUl.style.display='block'; 15 oUl.style.left=pos.x+'px'; 16 oUl.style.top=pos.y+'px'; 17 return false; //阻止默认事件就是阻止数遍右键 18 }; 19 20 document.onclick=function() 21 { 22 var oUl=document.getElementById('ul'); 23 oUl.style.display='none'; 24 }; 25 </script>
全部代码:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <style> 6 *{margin:0;padding:0;list-style:none;} 7 ul{width:200px;height:auto;border:solid 1px #ccc;display:none;position:absolute;} 8 li{margin-left:10px;} 9 </style> 10 <title>阻止默认事件</title> 11 <script> 12 function getPosition(ev) //获取页面到鼠标点的X Y坐标 13 { 14 var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; 15 var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft; 16 return{x: scrollLeft+ev.clientX,y: scrollTop+ev.clientY}; 17 }; 18 19 document.oncontextmenu=function(ev) //oncontextmenu=鼠标右键 20 { 21 var oUl=document.getElementById('ul'); 22 var oEvent=ev||event; 23 var pos=getPosition(oEvent); 24 oUl.style.display='block'; 25 oUl.style.left=pos.x+'px'; 26 oUl.style.top=pos.y+'px'; 27 return false; //阻止默认事件就是阻止鼠标右键 28 }; 29 30 document.onclick=function() 31 { 32 var oUl=document.getElementById('ul'); 33 oUl.style.display='none'; 34 }; 35 </script> 36 </head> 37 38 <body style="height:2000px;"> 39 <ul id="ul"> 40 <li>查看背景图片</li> 41 <li>全选</li> 42 <li>复制</li> 43 <li>粘贴</li> 44 </ul> 45 </body> 46 </html>