右键菜单原理:取消右键菜单oncontextmenu的默认事件,然后添加自定义样式。
一、阻止默认事件
ie:
window.event.returnValue = false;
w3c:
window,event.preventDafault();
二、阻止事件流
ie:
window.event.cancleBubble = true;
w3c:
window.event.stopPropagation();
三、代码
不用window获取窗口,因为该元素不支持ie8,采用document.body 能够兼容ie7+。
采用clientX而不是用pageX,理由同上。
rightclick.onmousedown:
鼠标按下,为取消右键菜单栏。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } body{ height: 600px; } .rightclick{ display: none; width: 100px; height: 160px; border-width: 1px 1px 0 1px; border-style: solid; border-color: black; background-color: rgba(242,242,242,0.6); border-radius: 4px; position: fixed; left: 0; top: 0; } .rightclick ul{ list-style: none; cursor: pointer; } .rightclick ul li{ text-align: center; font-family: "微软雅黑"; height: 31px; line-height: 31px; border-bottom: 1px solid #666; } </style> </head> <body> <div class="rightclick" id="rightclick"> <ul> <li>菜单1</li> <li>菜单2</li> <li>菜单3</li> <li>菜单4</li> <li>菜单5</li> </ul> </div> <script type="text/javascript"> document.body.oncontextmenu = function(e){ var ev = window.event || e; if(document.all){ ev.returnValue = false; //ie阻止默认事件 }else{ ev.preventDefault(); //w3c阻止默认事件 } var clientx = ev.clientX; var clienty = ev.clientY; var rightclick = document.getElementById("rightclick"); rightclick.style.display = "block"; rightclick.style.left = clientx+"px"; rightclick.style.top = clienty+"px"; } document.body.onmousedown = function(){ document.getElementById("rightclick").style.display = "none"; }; document.getElementById("rightclick").onclick = function(e){ var ev = window.event|| e; if(document.all){ ev.cancelBubble =true; // ie阻止事件流 }else{ ev.stopPropagation(); // w3c阻止事件流 } }; </script> </body> </html>
四、兼容性
chrome | firefox | ie7+ |
√ | √ | √ |
时间: 2024-10-29 12:29:17