如何使用jQuery获得鼠标点击按钮?
$('div').bind('click', function(){
alert('clicked');
});
这是由右键和左键点击触发的,有什么方法可以捕捉到鼠标右键点击?如果存在以下内容,我会很高兴:
$('div').bind('rightclick', function(){
alert('right mouse button is pressed');
});
如何使用jQuery获得鼠标点击按钮?
$('div').bind('click', function(){
alert('clicked');
});
这是由右键和左键点击触发的,有什么方法可以捕捉到鼠标右键点击?如果存在以下内容,我会很高兴:
$('div').bind('rightclick', function(){
alert('right mouse button is pressed');
});
当前回答
你也可以绑定到contextmenu并返回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/
其他回答
编辑:我在jQuery 1.7或以上版本中使用.on()将其更改为动态添加的元素:
$(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;
});
以防你有多种解决方案^^
编辑:Tim Down提出了一个很好的观点,它并不总是会是右键单击触发上下文菜单事件,但当上下文菜单键被按下时(这可以说是右键单击的替代)
从jQuery 1.1.3版本开始,事件。使事件正常化。keyCode和事件。charCode,这样就不必担心浏览器兼容性问题。关于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!');
}
});
你也可以绑定到contextmenu并返回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/
在我看来,稍微改编一下thevillagediot的答案会更简洁:
$('#element').bind('click', function(e) {
if (e.button == 2) {
alert("Right click");
}
else {
alert("Some other click");
}
}
编辑:JQuery提供了一个e.t it属性,在左、中、右单击时分别返回1、2、3。所以你也可以使用if (e.which == 3) {alert("right click");}
请参见:“使用中点击触发onclick事件”的回答
你可以试试下面的代码:
event.button
返回值:一个数字,表示鼠标事件发生时按下的鼠标按钮。
可能的值:
0:鼠标左键 1:车轮按钮或中间按钮(如果有) 2:鼠标右键 注意:ie8及更早版本有不同的返回值:
1:鼠标左键 2:鼠标右键 4:滚轮按钮或中间按钮(如果有的话)注意:对于左侧配置的鼠标,返回值颠倒