如何编写 .click 的 JQuery 等效项以进行中键单击

How can I write the JQuery equivalent of .click for middle click?

本文关键字:进行中 单击 何编写 click JQuery      更新时间:2023-09-26
我想

在用户中键单击元素时触发一个操作。

.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);

尝试使用鼠标向上而不是单击,

$("a").mouseup(function(e) {
  e.preventDefault();
  alert(e.which);
});

试试这个...

$(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;
    }
});

js小提琴:http://jsfiddle.net/rfornal/muqhnrt7/

然后,你可以做这样的事情...

$(document).on("mousedown", function(e){
    switch(e.which)
    {
        case 1:
        case 2:
            alert("left or middle button");
        break;
    }
});

jsFiddle for this this: http://jsfiddle.net/rfornal/muqhnrt7/1/

>click适用于中键单击(查找e.which === 2),在允许它的浏览器上(这似乎不包括Firefox)。

对于右键单击,它是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>

$('a').click(function(e) {
    e.preventDefault();
    var isMiddle = event.which == null && event.button == 4 || /* IE */
                   event.which == 2; /* Others */
    if (!isMiddle) return;
    //
    // Handle the middleclick
    //
});