当用户用鼠标中键点击一个元素时,我想触发一个动作。
.click仅捕获左击(右?或者至少在我的firefox实验中是这样的)。
我知道我可以简单地创建一个mousedown/mouseup事件并检测被点击的按钮,但是我不确定我是否会错过.click所具有的各种兼容性/安全性等特性。
我可以编写哪个.middleclick函数来尽可能接近与.click相同的行为
下面是我的实验
// this does NOT work for middle-click or right-click
$("a").click(function(e) {
e.preventDefault();
alert(e.which);
});
// this DOES work for all three types of click (although fwiw for right-click
// it does not prevent contextual menu from coming up in FF
document.addEventListener("click", function(e){
e.preventDefault();
alert(e.which);
}, true);发布于 2015-01-23 02:06:15
试试这个。
$(document).on("mousedown", function(e){
switch(e.which)
{
case 1:
alert("1");
break;
case 2:
alert("2");
-- middle button
break;
case 3:
alert("3");
break;
}
});jsFiddle:http://jsfiddle.net/rfornal/muqhnrt7/
然后,你可以做这样的事情...
$(document).on("mousedown", function(e){
switch(e.which)
{
case 1:
case 2:
alert("left or middle button");
break;
}
});本例的jsFiddle:http://jsfiddle.net/rfornal/muqhnrt7/1/
发布于 2015-01-23 02:08:06
尝试使用鼠标向上而不是单击,
$("a").mouseup(function(e) {
e.preventDefault();
alert(e.which);
});发布于 2015-01-23 02:11:20
在允许的浏览器(这似乎不包括火狐)上,click适用于鼠标中键点击(查找e.which === 2)。
对于右键单击,它是contextmenu事件,您的浏览器可能支持也可能不支持。
示例:
// Responds to middle- and right-click (on browsers offering
// contextmenu), not to left-click (because of the `if`)
$("a").on("click contextmenu", function(e) {
if (e.type === "click" && e.which === 2) {
snippet.log("Got " + e.type + " event with e.which === 2");
} else if (e.type === "contextmenu") {
snippet.log("Got " + e.type + " event");
}
e.preventDefault();
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#">Click Me</a>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
https://stackoverflow.com/questions/28095637
复制相似问题