如何使用jQuery获取点击的鼠标按钮?
$('div').bind('click', function(){
alert('clicked');
});
这是由左右点击触发的,能够捕捉到鼠标右键的方式是什么?如果存在以下内容,我会很高兴:
$('div').bind('rightclick', function(){
alert('right mouse button is pressed');
});
答案 0 :(得分:868)
从jQuery版本1.1.3开始,event.which
规范化了event.keyCode
和event.charCode
,因此您无需担心浏览器兼容性问题。 Documentation on 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!');
}
});
答案 1 :(得分:246)
编辑:我在jQuery 1.7或更高版本中使用.on()
将其更改为适用于动态添加的元素:
$(document).on("contextmenu", ".element", function(e){
alert('Context Menu event has fired!');
return false;
});
[原始帖子的开头]这对我有用:
$('.element').bind("contextmenu",function(e){
alert('Context Menu event has fired!');
return false;
});
如果您涉及多个解决方案^^
编辑:Tim Down提出了一个很好的观点,即它不会总是right-click
触发contextmenu
事件,而且当上下文菜单键是按下(可以说是right-click
的替代品)
答案 2 :(得分:82)
通过在鼠标事件上检查事件对象的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! */
}
});
答案 3 :(得分:38)
您还可以bind
到contextmenu
和return 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.
答案 4 :(得分:30)
<击> 撞击>
<击>$("#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>
答案 5 :(得分:18)
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});
答案 6 :(得分:14)
有很多非常好的答案,但我只想谈谈IE9和IE之间的一个主要区别&lt; 9使用event.button
时。
根据旧的Microsoft event.button
规范,代码与W3C使用的代码不同。 W3C仅考虑3个案例:
event.button === 1
event.button === 3
event.button === 2
在较旧的Internet Explorer中,微软在按下按钮时略微翻了一下,有8种情况:
event.button === 0
或000 event.button === 1
或001 event.button === 2
或010 event.button === 3
或011 event.button === 4
或100 event.button === 5
或101 event.button === 6
或110 event.button === 7
或111 尽管理论上它应该如何工作,但是没有Internet Explorer支持同时按下两个或三个按钮的情况。我提到它是因为W3C标准在理论上甚至不能支持这一点。
答案 7 :(得分:8)
在我看来,对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"); }
答案 8 :(得分:3)
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...
}
});
答案 9 :(得分:1)
$("body").on({
click: function(){alert("left click");},
contextmenu: function(){alert("right click");}
});
答案 10 :(得分:1)
如果您正在寻找&#34;更好的Javascript鼠标事件&#34;
看看这个跨浏览器的普通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)}();
答案 11 :(得分:0)
$(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;
}
});
答案 12 :(得分:0)
$.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");
});
答案 13 :(得分:0)
还有一种方法,没有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
}
});
答案 14 :(得分:0)
使用jquery,您可以使用event object type
jQuery(".element").on("click contextmenu", function(e){
if(e.type == "contextmenu") {
alert("Right click");
}
});
答案 15 :(得分:-1)
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});
答案 16 :(得分:-1)
旧帖子 - 但我认为会与上面询问所有鼠标点击事件类型的人分享完整的答案。
添加此脚本使其适用于整个页面:
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);
注意:确保在被点击的元素上'return false;' - 这真的很重要。
干杯!