如何用jQuery区分鼠标左键和右键

如何使用jQuery获取单击的鼠标按钮?

$('div').bind('click', function(){ alert('clicked'); }); 

这是由左右键单击触发的,能够捕获鼠标右键的方式是什么? 如果存在以下内容,我会很高兴:

 $('div').bind('rightclick', function(){ alert('right mouse button is pressed'); }); 

从jQuery版本1.1.3开始, event.which规范化event.keyCodeevent.which ,因此您不必担心浏览器兼容性问题。 关于event.which文档

event.which分别为左,中,右鼠标按钮分别给出1,2或3,这样:

 $('#element').mousedown(function(event) { switch (event.which) { case 1: alert('Left Mouse button pressed.'); break; case 2: alert('Middle Mouse button pressed.'); break; case 3: alert('Right Mouse button pressed.'); break; default: alert('You have a strange Mouse!'); } }); 

编辑 :我在jQuery 1.7或更高版本中使用.on()将其更改为动态添加元素:

 $(document).on("contextmenu", ".element", function(e){ alert('Context Menu event has fired!'); return false; }); 

演示: jsfiddle.net/Kn9s7/5

[原始post的开头]这对我有用:

 $('.element').bind("contextmenu",function(e){ alert('Context Menu event has fired!'); return false; }); 

如果你进入多个解决方案^^

编辑 :Tim Down提出了一个很好的观点,即它并不总是一个right-click触发contextmenu事件,而且当按下上下文菜单键时(可以说是right-click的替代)

通过检查鼠标事件上事件对象的which属性,您可以轻松地告诉按下了哪个鼠标按钮:

 /* 1 = Left mouse button 2 = Centre mouse button 3 = Right mouse button */ $([selector]).mousedown(function(e) { if (e.which === 3) { /* Right mouse button was clicked! */ } }); 

您还可以bindcontextmenureturn false

 $('selector').bind('contextmenu', function(e){ e.preventDefault(); //code return false; }); 

演示: http : //jsfiddle.net/maniator/WS9S2/

或者你可以制作一个同样的快速插件:

 (function( $ ) { $.fn.rightClick = function(method) { $(this).bind('contextmenu rightclick', function(e){ e.preventDefault(); method(); return false; }); }; })( jQuery ); 

演示: http : //jsfiddle.net/maniator/WS9S2/2/


使用.on(...) jQuery> = 1.7:

 $(document).on("contextmenu", "selector", function(e){ e.preventDefault(); //code return false; }); //does not have to use `document`, it could be any container element. 

演示: http : //jsfiddle.net/maniator/WS9S2/283/

 $("#element").live('click', function(e) { if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) { alert("Left Button"); } else if(e.button == 2){ alert("Right Button"); } }); 

更新当前的状态:

 var $log = $("div.log"); $("div.target").on("mousedown", function() { $log.text("Which: " + event.which); if (event.which === 1) { $(this).removeClass("right middle").addClass("left"); } else if (event.which === 2) { $(this).removeClass("left right").addClass("middle"); } else if (event.which === 3) { $(this).removeClass("left middle").addClass("right"); } }); 
 div.target { border: 1px solid blue; height: 100px; width: 100px; } div.target.left { background-color: #0faf3d; } div.target.right { background-color: #f093df; } div.target.middle { background-color: #00afd3; } div.log { text-align: left; color: #f00; } 
  
 $.event.special.rightclick = { bindType: "contextmenu", delegateType: "contextmenu" }; $(document).on("rightclick", "div", function() { console.log("hello"); return false; }); 

http://jsfiddle.net/SRX3y/8/

有很多非常好的答案,但我只是想在使用event.buttonevent.button IE9和IE <9之间的一个主要区别。

根据旧的Microsoft event.button规范,代码与W3C使用的代码不同。 W3C仅考虑3个案例:

  1. 单击鼠标左键 – event.button === 1
  2. 单击鼠标右键 – event.button === 3
  3. 单击鼠标中键 – event.button === 2

在较旧的Internet Explorer中,微软正在为按下的按钮翻转一下,有8种情况:

  1. 没有点击按钮 – event.button === 0或000
  2. 单击左键 – event.button === 1或001
  3. 单击右键 – event.button === 2或010
  4. 单击左右按钮 – event.button === 3或011
  5. 单击中间按钮 – event.button === 4或100
  6. 单击中间和左侧按钮 – event.button === 5或101
  7. 单击中间和右侧按钮 – event.button === 6或110
  8. 单击所有3个按钮 – event.button === 7或111

尽管事实上这在理论上应该如何工作,但是没有Internet Explorer支持同时按下两个或三个按钮的情况。 我提到它是因为W3C标准在理论上甚至不能支持这一点。

在我看来,对TheVillageIdiot的回答略有改动会更清晰:

 $('#element').bind('click', function(e) { if (e.button == 2) { alert("Right click"); } else { alert("Some other click"); } } 

编辑:JQuery提供了一个e.which属性,分别为左,中,右三次返回1,2,3。 所以你也可以使用if (e.which == 3) { alert("right click"); } if (e.which == 3) { alert("right click"); }

另请参阅: “使用中键单击触发onclick事件”的答案

event.which === 1确保它是左键单击(使用jQuery时)。

但你也应该考虑修改键: ctrl cmd shift alt

如果您只想捕捉简单的,未经修改的左键单击,您可以执行以下操作:

 var isSimpleClick = function (event) { return !( event.which !== 1 || // not a left click event.metaKey || // "open link in new tab" (mac) event.ctrlKey || // "open link in new tab" (windows/linux) event.shiftKey || // "open link in new window" event.altKey // "save link as" ); }; $('a').on('click', function (event) { if (isSimpleClick(event)) { event.preventDefault(); // do something... } }); 

如果您正在寻找允许的“更好的Javascript鼠标事件”

  • 离开了mousedown
  • 中间的mousedown
  • 对了mousedown
  • 留下了鼠标
  • 中间的鼠标
  • 正确的鼠标
  • 左键单击
  • 中间点击
  • 右键点击
  • 鼠标滚轮
  • 鼠标滚轮

看看这个跨浏览器的普通javascript会触发上述事件,并消除头痛的工作。 只需将其复制并粘贴到脚本的头部,或将其包含在文档的文件中即可。 然后绑定你的事件,参考下面的下一个代码块,它显示了捕获事件和触发分配给它们的函数的jquery示例,尽管这也适用于普通的javascript绑定。

如果您有兴趣看到它的工作,请看看jsFiddle: https ://jsfiddle.net/BNefn/

 /** Better Javascript Mouse Events Author: Casey Childers **/ (function(){ // use addEvent cross-browser shim: https://gist.github.com/dciccale/5394590/ var addEvent = function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}}; /* This function detects what mouse button was used, left, right, middle, or middle scroll either direction */ function GetMouseButton(e) { e = window.event || e; // Normalize event variable var button = ''; if (e.type == 'mousedown' || e.type == 'click' || e.type == 'contextmenu' || e.type == 'mouseup') { if (e.which == null) { button = (e.button < 2) ? "left" : ((e.button == 4) ? "middle" : "right"); } else { button = (e.which < 2) ? "left" : ((e.which == 2) ? "middle" : "right"); } } else { var direction = e.detail ? e.detail * (-120) : e.wheelDelta; switch (direction) { case 120: case 240: case 360: button = "up"; break; case -120: case -240: case -360: button = "down"; break; } } var type = e.type if(e.type == 'contextmenu') {type = "click";} if(e.type == 'DOMMouseScroll') {type = "mousewheel";} switch(button) { case 'contextmenu': case 'left': case 'middle': case 'up': case 'down': case 'right': if (document.createEvent) { event = new Event(type+':'+button); e.target.dispatchEvent(event); } else { event = document.createEventObject(); e.target.fireEvent('on'+type+':'+button, event); } break; } } addEvent(window, 'mousedown', GetMouseButton); addEvent(window, 'mouseup', GetMouseButton); addEvent(window, 'click', GetMouseButton); addEvent(window, 'contextmenu', GetMouseButton); /* One of FireFox's browser versions doesn't recognize mousewheel, we account for that in this line */ var MouseWheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel"; addEvent(window, MouseWheelEvent, GetMouseButton); })(); 

更好的鼠标单击事件示例(为简单起见使用jquery,但上面的工作将跨浏览器并触发相同的事件名称,IE在名称前使用)

 

对于那些需要缩小版本的人来说......

 !function(){function e(e){e=window.event||e;var t="";if("mousedown"==e.type||"click"==e.type||"contextmenu"==e.type||"mouseup"==e.type)t=null==e.which?e.button<2?"left":4==e.button?"middle":"right":e.which<2?"left":2==e.which?"middle":"right";else{var n=e.detail?-120*e.detail:e.wheelDelta;switch(n){case 120:case 240:case 360:t="up";break;case-120:case-240:case-360:t="down"}}var c=e.type;switch("contextmenu"==e.type&&(c="click"),"DOMMouseScroll"==e.type&&(c="mousewheel"),t){case"contextmenu":case"left":case"middle":case"up":case"down":case"right":document.createEvent?(event=new Event(c+":"+t),e.target.dispatchEvent(event)):(event=document.createEventObject(),e.target.fireEvent("on"+c+":"+t,event))}}var t=function(e,t,n){try{e.addEventListener(t,n,!1)}catch(c){e.attachEvent("on"+t,n)}};t(window,"mousedown",e),t(window,"mouseup",e),t(window,"click",e),t(window,"contextmenu",e);var n=/Firefox/i.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel";t(window,n,e)}(); 
 $("body").on({ click: function(){alert("left click");}, contextmenu: function(){alert("right click");} }); 
 $(document).ready(function () { var resizing = false; var frame = $("#frame"); var origHeightFrame = frame.height(); var origwidthFrame = frame.width(); var origPosYGrip = $("#frame-grip").offset().top; var origPosXGrip = $("#frame-grip").offset().left; var gripHeight = $("#frame-grip").height(); var gripWidth = $("#frame-grip").width(); $("#frame-grip").mouseup(function (e) { resizing = false; }); $("#frame-grip").mousedown(function (e) { resizing = true; }); document.onmousemove = getMousepoints; var mousex = 0, mousey = 0, scrollTop = 0, scrollLeft = 0; function getMousepoints() { if (resizing) { var MouseBtnClick = event.which; if (MouseBtnClick == 1) { scrollTop = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop; scrollLeft = document.documentElement ? document.documentElement.scrollLeft : document.body.scrollLeft; mousex = event.clientX + scrollLeft; mousey = event.clientY + scrollTop; frame.height(mousey); frame.width(mousex); } else { resizing = false; } } return true; } }); 

使用jquery,您可以使用event object type

 jQuery(".element").on("click contextmenu", function(e){ if(e.type == "contextmenu") { alert("Right click"); } }); 

还有一种方法,没有JQuery就可以做到!

看看这个:

 document.addEventListener("mousedown", function(evt) { switch(evt.buttons) { case 1: // left mouse case 2: // right mouse case 3: // middle mouse <- I didn't tested that, I just got a touchpad } }); 
 $.fn.rightclick = function(func){ $(this).mousedown(function(event){ if(event.button == 2) { var oncontextmenu = document.oncontextmenu; document.oncontextmenu = function(){return false;}; setTimeout(function(){document.oncontextmenu = oncontextmenu;},300); func(event); return false; } }); }; $('.item').rightclick(function(e){ alert("item"); }); 
  $.event.special.rightclick = { bindType: "contextmenu", delegateType: "contextmenu" }; $(document).on("rightclick", "div", function() { console.log("hello"); return false; });