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

如何使用jQuery获得鼠标点击按钮?

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

这是由右键和左键点击触发的,有什么方法可以捕捉到鼠标右键点击?如果存在以下内容,我会很高兴:

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

<罢工>

$("#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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target"></div>
<div class="log"></div>

你可以通过检查鼠标事件的事件对象的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! */
}
});

在我看来,稍微改编一下thevillagediot的答案会更简洁:

$('#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"); }

参见:对“使用中点击触发onclick事件”的回答

在jQuery 1.1.3版本中,event.which规范化了event.keyCodeevent.charCode,因此您不必担心浏览器兼容性问题。# EYZ4

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!');
}
});

编辑:我改变了它的工作动态添加的元素使用.on()在jQuery 1.7或以上:

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

演示:# EYZ0

[原文开始]这对我来说是有效的:

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

以防你有多种解决方案^^

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

你也可以bindcontextmenureturn false:

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

演示:# EYZ0

或者你可以做一个快速插件,做同样的事情:

(function( $ ) {
$.fn.rightClick = function(method) {


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


};
})( jQuery );

演示:# EYZ0


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.

演示:# EYZ0

$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};


$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});

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

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

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

  1. 点击鼠标左键- event.button === 1
  2. 点击鼠标右键- event.button === 3
  3. 点击鼠标中间按钮- event.button === 2

然而,在老式的ie浏览器中,微软会为按下的按钮翻转一些,有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

尽管理论上它应该是这样工作的,但没有任何ie浏览器支持同时按下两个或三个按钮的情况。我之所以提到它,是因为W3C标准甚至在理论上不支持这一点。

$(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;


}




});

event.which === 1确保它是一个左键点击(当使用jQuery时)。

但你也应该考虑修改键:ctrlcmd转变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...
}
});
    $.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};


$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});

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
}
});

如果你正在寻找“更好的Javascript鼠标事件”,其中允许

  • 离开mousedown
  • 中间mousedown
  • 对mousedown
  • 离开mouseup
  • 中间mouseup
  • 对mouseup
  • 左键点击
  • 中间点击
  • 右击
  • mousewheel起来
  • mousewheel下来

看看这个跨浏览器的正常javascript触发上述事件,并消除了头痛的工作。只需将其复制并粘贴到脚本头部,或将其包含在文档的<head>中的文件中。然后绑定你的事件,参考下面的代码块,它显示了一个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使用在名称之前)

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

对于那些想知道是否应该在香草JS中使用event.which的人:现在是弃用,所以更喜欢使用event.buttons

使用这个方法和(mousedown)事件:

  • 左键按与1相关联
  • 右击按与2相关联
  • 滚动按钮按下与4相关联

(mouseup)事件将返回相同的数字,而不是0

来源:https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons

一个老旧的帖子,但我想分享完整的答案给人们问以上关于所有鼠标点击事件类型

添加这个脚本,使它适用于整个页面:

var onMousedown = function (e) {
if (e.which === 1) {/* Left Mouse Click */}
else if (e.which === 2) {/* Middle Mouse Click */}
else if (e.which === 3) {/* Right Mouse Click */}
};
clickArea.addEventListener("mousedown", onMousedown);

注意:确保在被点击的元素上使用”返回false,“,这非常重要。

干杯!

<!DOCTYPE html>
<html>
<head>
<title>JS Mouse Events - Button Demo</title>
</head>
<body>
<button id="btn">Click me with any mouse button: left, right, middle, ...</button>
<p id="message"></p>
<script>
let btn = document.querySelector('#btn');


// disable context menu when right-mouse clicked
btn.addEventListener('contextmenu', (e) => {
e.preventDefault();
});


// show the mouse event message
btn.addEventListener('mouseup', (e) => {
let msg = document.querySelector('#message');
switch (e.button) {
case 0:
msg.textContent = 'Left mouse button clicked.';
break;
case 1:
msg.textContent = 'Middle mouse button clicked.';
break;
case 2:
msg.textContent = 'Right mouse button clicked.';
break;
default:
msg.textContent = `Unknown mouse button code: ${event.button}`;
}
});
</script>
</body>
</html>

你可以试试下面的代码:

event.button

返回值:一个数字,表示鼠标事件发生时按下的鼠标按钮。

可能的值:

0:鼠标左键 1:车轮按钮或中间按钮(如果有) 2:鼠标右键 注意:ie8及之前版本有不同的返回值:

1:鼠标左键 2:鼠标右键 4:滚轮按钮或中间按钮(如果存在)注:对于左旋配置的鼠标,返回值颠倒