JavaScript模擬右鍵菜單
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>右鍵菜單</title> <style type="text/css"> *{ margin: 0; padding: 0; } #menu{ width: 254px; /*background-color: #ccc;*/ font-size: 12px; position: fixed; top: 0px; left: 0px; /*height: 240px;*/ /*padding-left: 26px;*/ padding-top: 2px; border:1px solid #ccc; display: none; } #menu li{ list-style: none; line-height: 25px; margin-left: -1px; padding-left: 26px; } #menu li:hover{ background-color: #4281f4; color: #fff; } </style> </head> <body> <ul id="menu"> <li>返回(B)</li> <li>前進(F)</li> <li>從新載入(R)</li> <li>另存為(A)</li> <li>列印(P)</li> <li>查看網頁源代碼(V)</li> <li>查看網頁信息(I)</li> <li>審查元素(N)</li> </ul> <script type="text/javascript"> var menu = document.getElementById("menu"); document.oncontextmenu =function(e){ var e = e ||window.event;//相容 console.log(e.clientX,e.clientY); console.log(e); //單擊顯示div menu.style.display = "block"; //設置定義 //判斷滑鼠坐標是否大於視口寬度-塊本身寬度 var cakLeft = (e.clientX > document.documentElement.clientWidth - menu.offsetWidth)?(document.documentElement.clientWidth - menu.offsetWidth):e.clientX; var cakTop = (e.clientY > document.documentElement.clientHeight - menu.offsetHeight)?(document.documentElement.clientHeight - menu.offsetHeight):e.clientY; menu.style.left = cakLeft + "px"; menu.style.top = cakTop + "px"; return false; } menu.onclick = function(e) { var e = e || window.event; e.cancelBubble = true; //阻止冒泡。 } document.onclick = function() { menu.style.display = "none"; } </script> </body> </html>