如何区分jQuery的左右点击鼠标

你如何获得使用jQuery点击鼠标button?

$('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将分别给左,中,右鼠标button1,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()dynamic添加元素:

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

演示: jsfiddle.net/Kn9s7/5

[原始文章的开始]这是我工作的:

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

如果你是多种解决scheme^^

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

您可以通过检查鼠标事件上的事件对象的which属性轻松地确定按下了哪个鼠标button:

 /* 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"); } }); 
 $.event.special.rightclick = { bindType: "contextmenu", delegateType: "contextmenu" }; $(document).on("rightclick", "div", function() { console.log("hello"); return false; }); 

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

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

根据旧的微软对event.button的规范,代码与W3C使用的代码不同。 W3C只考虑3种情况:

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

在较旧的互联网浏览器中,微软正在按下button,有8种情况:

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

尽pipe这在理论上应该如何工作,但Internet Explorer从未支持同时按下两个或三个button的情况。 我提到它是因为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
  • 离开mouseup
  • 中间mouseup
  • 正确的mouseup
  • 左键单击
  • 中间点击
  • 右键点击
  • 鼠标向上滚动
  • 鼠标滚下来

看看这个跨浏览器的正常的JavaScript触发上述事件,并消除头痛的工作。 只需将其复制并粘贴到脚本的头部,或将其包含在文档的<head>文件中即可。 然后绑定你的事件,参考下面的代码块,其中显示了捕获事件和触发分配给它们的函数的jQuery示例,尽pipe这也适用于普通的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名称前使用)

 <div id="Test"></div> <script type="text/javascript"> $('#Test').on('mouseup',function(e){$(this).append(e.type+'<br />');}) .on('mouseup:left',function(e){$(this).append(e.type+'<br />');}) .on('mouseup:middle',function(e){$(this).append(e.type+'<br />');}) .on('mouseup:right',function(e){$(this).append(e.type+'<br />');}) .on('click',function(e){$(this).append(e.type+'<br />');}) .on('click:left',function(e){$(this).append(e.type+'<br />');}) .on('click:middle',function(e){$(this).append(e.type+'<br />');}) .on('click:right',function(e){$(this).append(e.type+'<br />');}) .on('mousedown',function(e){$(this).html('').append(e.type+'<br />');}) .on('mousedown:left',function(e){$(this).append(e.type+'<br />');}) .on('mousedown:middle',function(e){$(this).append(e.type+'<br />');}) .on('mousedown:right',function(e){$(this).append(e.type+'<br />');}) .on('mousewheel',function(e){$(this).append(e.type+'<br />');}) .on('mousewheel:up',function(e){$(this).append(e.type+'<br />');}) .on('mousewheel:down',function(e){$(this).append(e.type+'<br />');}) ; </script> 

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

 !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)}(); 
 $(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; }); 
 $("body").on({ click: function(){alert("left click");}, contextmenu: function(){alert("right click");} });