右键点击触发是浏览器的默认菜单事件contextmenu,你可以选择阻止它,使用event.preventDefault();或者return false;。
想要定义右键点击事件,关注的是mouseup或者mousedown事件,使用event获取点击的键:
Js中使用event. button---0,1,2分别是左键、滚轮、右键
Jq中使用event.which---1,2,3分别是左键、滚轮、右键
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"/> <title>鼠标事件</title> <script src=‘/static/Lib/jquery/jquery-3.3.1.min.js‘></script> <script src=‘js/jquery-3.3.1.min.js‘></script> <style> #f1{ padding:10px; background:black; } #f2{ padding:10px; background:red; } #f3{ padding:10px; } #test{ background:black; color:white; padding:2px; } </style> </head> <body> <div id="f1"> <button id="button1">javascript</button> </div> <div id="f2"> <button id="button2">jquery</button> </div> <div id=‘f3‘><a href="worker.js" target="_blank" id=‘test‘><span></span>超链接</a></div> <script type="text/javascript"> function say(){ alert(this.innerHTML); } window.onload= function(){ //实现右键单击事件 //js //关闭鼠标右键默认事件 document.getElementById("button1").oncontextmenu = function(e){ e.preventDefault(); }; //设置鼠标按键事件 document.getElementById("button1").onmousedown = function(e){ if(e.button ==2){ console.log("你点了右键"); }else if(e.button ==0){ console.log("你点了左键"); }else if(e.button ==1){ console.log("你点了滚轮"); } } //jq //关闭鼠标右键默认事件 $(‘#button2‘).bind("contextmenu", function(){ return false; }); //设置鼠标按键事件 $(‘#button2‘).on(‘mousedown‘, function(e){ if (1 == e.which) { console.log("你点了左键"); } else if (2 == e.which) { console.log("你点了滚轮"); } else if (3 == e.which) { console.log("你点了右键"); } }); }; </script> </body> </html>
示例html和js代码
https://www.cnblogs.com/chenluomenggongzi/p/5777545.html
https://blog.csdn.net/u014291497/article/details/52267604
原文地址:https://www.cnblogs.com/liwxmyself/p/10249037.html
时间: 2024-10-07 19:37:09