关于JS右键菜单
直接先上代码。
<!DOCTYPE html> <html lang="zh"> <head> <title>自定义右键菜单</title> <meta charset="utf-8"> <style type="text/css"> *{ margin: 0; padding: 0; } html,body{ height: 100%; position: relative; overflow-y: hidden; } .div1{ width: 45%; height: 100%; background-color:rgba(89, 199, 203, 0.25); float: left; } .div2{ width: 45%; height: 100%; float: right; background-color:rgba(89, 199, 203, 0.25); } .menu{ position: absolute; display: none; } .menu ul li{ list-style: none; display: inline-block; width: 176px; height: 31px; line-height: 31px; text-align: center; border: 1px solid #e2e2e2; background-color: white; } .menu ul{ width: 140px; } .menu ul li a{ text-decoration: none; color: black; } input{ display: block; border: 1px solid; } </style> </head> <body> <div class="div1" > laaaaaaaaaaaaaaaaaaaa </div> <div class="div2"></div> <div class="menu"> <ul> <li onclick='copy()' ><a href="javascript:;">复制</a></li> <li onclick='zhan()'><a href="javascript:;">粘贴</a></li> <li><a href="javascript:;">打开</a></li> </ul> </div> <script type="text/javascript"> var div1 = document.getElementsByClassName('div1')[0]; var menu = document.getElementsByClassName('menu')[0]; function mousePosition(ev){ if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY};} return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop - document.body.clientTop }; } div1.oncontextmenu=function(e){return false;} menu.oncontextmenu=function(e){return false;} div1.onmouseup = function(e) { if(e.button==2){ e= event|| window.event; var shu = mousePosition(e); menu.style.display = "block"; menu.style.left = shu.x+"px"; menu.style.top = shu.y+"px"; menu.onclick = function() { menu.style.display = "none"; } div1.onclick = function() { menu.style.display = "none"; } }else{ return false; } } var a=document.getElementsByTagName('a'); function copy(){ var aa = document.execCommand('copy',false,null); console.log(aa); } </script> </body> </html>
思路:1.阻止原网页右键菜单
2.阻止菜单的右键菜单->当鼠标点击松开之后onmouseup(如果是onmousedown会失去焦点,copy失败),判断点击的是左键还是右键
3.如果是右键(e.button==2)显示菜单->(在右键菜单打开时)点击其他地方与点击菜单按钮,菜单消失。
4.实现菜单功能。(粘贴因为浏览器安全问题。不能获取用户剪切板,所以未能实现)。
感谢 YL小姐姐 分享的知识