如何使用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');
});
当前回答
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return 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>
你也可以绑定到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/
通过查看鼠标事件的事件对象的属性,你可以很容易地知道按下了哪个鼠标按钮:
/*
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! */
}
});
使用jquery,你可以使用事件对象类型
jQuery(".element").on("click contextmenu", function(e){
if(e.type == "contextmenu") {
alert("Right click");
}
});
老旧的帖子,但想分享完整的答案,人们问上面所有的鼠标点击事件类型。
添加这个脚本,使它适用于整个页面:
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;' -这真的很重要。
干杯!