HTML自定義右鍵菜單oncontextmenu
阿新 • • 發佈:2017-09-18
click isp 樣式 true 菜單 menu tro ret 自定義
右鍵菜單原理:取消右鍵菜單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+ |
√ | √ | √ |
HTML自定義右鍵菜單oncontextmenu