本文实例为大家分享了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>
希望本文所述对大家学习javascript程序设计有所帮助。