自定义右键菜单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义右键菜单</title> <style> div{width: 400px;height: 400px;background:cyan;} ul{width: 80px;height: 100px;background: orange;position:absolute;display:none;} </style> <script> window.onload =function(){ //阻止系统自带右键菜单 document.oncontextmenu = function(){ return false; } //自定义右键菜单 var oDiv = document.getElementById('div'); var oUl = document.getElementById('menu'); oDiv.onmousedown = function(ev){ //获取事件对象 var e = ev || window.event; //判断按下的是否为右键 if(e.button == 2){ oUl.style.display = 'block'; oUl.style.left = e.clientX+'px'; oUl.style.top = e.clientY+'px'; }else{//点击别的键时关闭自定义菜单 oUl.style.display = 'none'; } } } </script> </head> <body> <div id="div"></div> <ul id="menu"> <li>选项1</li> <li>选项2</li> <li>选项3</li> </ul> </body> </html>
浏览器效果