jQuery如何区分鼠标左键单击和右键单击 [英] How to distinguish between left and right mouse click with jQuery
本文介绍了jQuery如何区分鼠标左键单击和右键单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 jQuery 获取点击的鼠标按钮?
How do you obtain the clicked mouse button using jQuery?
$('div').bind('click', function(){
alert('clicked');
});
这个是左右点击都触发的,有什么办法可以抓到鼠标右键?如果存在以下内容,我会很高兴:
this is triggered by both right and left click, what is the way of being able to catch right mouse click? I'd be happy if something like below exists:
$('div').bind('rightclick', function(){
alert('right mouse button is pressed');
});
推荐答案
从 jQuery 1.1.3 版开始,event.which
规范化了 event.keyCode
和 event.charCode
这样你就不用担心浏览器兼容性问题了.关于event.which
As of jQuery version 1.1.3, event.which
normalizes event.keyCode
and event.charCode
so you don't have to worry about browser compatibility issues. Documentation on event.which
event.which
将分别为鼠标左键、中键和右键给出 1、2 或 3,因此:
event.which
will give 1, 2 or 3 for left, middle and right mouse buttons respectively so:
$('#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如何区分鼠标左键单击和右键单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文