3

在javascript中捕获鼠标左键和右键的最佳方法是什么?我没有使用 jQuery(它在我的学习列表中的下一个),现在只使用 javascript。基本上,我想做类似的事情

 onClick()=javascript:rightClickFunction() // do right click function
 onContextMenu()=javascript:leftClickFunction() /
 onBoth() ???

我在stackoverflow上唯一能找到的是: 如何用jQuery区分鼠标左键和右键

我应该如何捕获双击?我可以检查在 R 和 L 按钮例程期间是否也单击了相反的按钮?

4

3 回答 3

11

您可以使用一些布尔变量来跟踪哪些鼠标按钮被按下,如下所示:

var leftButtonDown = false;
var rightButtonDown = false;

$(document).mousedown(function() {
    if(e.which == 1) {
        leftButtonDown = true;
    } else if (e.which == 3) {
        rightButtonDown = true;
    }
});

$(document).mouseup(function() {
    if(e.which == 1) {
        leftButtonDown = false;
    } else if (e.which == 3) {
        rightButtonDown = false;
    }
});

$(document).click(function() {
    if(leftButtonDown && rightButtonDown) {
        // left and right buttons are clicked at the same time
    }
});

如果两个布尔值都为真,则鼠标右键和左键都被单击。

于 2012-05-15T21:15:03.237 回答
2

基于Elliot回答的纯 Javascript 解决方案:

var leftButtonDown = false;
var rightButtonDown = false;

document.addEventListener("mousedown", function () {
    if (e.which == 1) {
        leftButtonDown = true;
    } else if (e.which == 3) {
        rightButtonDown = true;
    }
});

document.addEventListener("mouseup", function () {
    if (e.which == 1) {
        leftButtonDown = false;
    } else if (e.which == 3) {
        rightButtonDown = false;
    }
});

document.addEventListener("click", function () {
    if (leftButtonDown && rightButtonDown) {
        // Click with both LMB and RMB.
    }
});
于 2016-11-11T16:00:10.257 回答
1

对于仍然对最近的答案感兴趣的任何人,因为 event.which 已被弃用,您可以将以下代码与 ES6 语法一起使用。

let leftButtonDown = false;
let rightButtonDown = false;

document.addEventListener("mousedown", (e) => {
    // left click
    if (e.button === 0) {
        leftButtonDown = true;
    }
    // right click
    if (e.button === 2) {
        rightButtonDown = true;
    }
    if (leftButtonDown && rightButtonDown) {
        // insert code here
    }
});

document.addEventListener("mouseup", (e) => {
    if (e.button === 0) {
        leftButtonDown = false;
    }
    if (e.button === 2) {
        rightButtonDown = false;
    }
});

如果您想阻止弹出上下文菜单,您可以尝试以下变体:

let leftButtonDown = false;
let rightButtonDown = false;

document.addEventListener("mousedown", (e) => {
    // left click
    if (e.button === 0) {
        leftButtonDown = true;
    }
    // right click
    if (e.button === 2) {
        rightButtonDown = true;
    }
    if (leftButtonDown && rightButtonDown) {
        // insert code here
    }
});

document.addEventListener("mouseup", (e) => {
    if (e.button === 0) {
        leftButtonDown = false;
    }
});

document.addEventListener("contextmenu", (e) => {
    if (leftButtonDown && rightButtonDown) {
        e.preventDefault();
    }
    rightButtonDown = false;
});

现代浏览器鼠标按键映射:

  • 左键 = 0
  • 中键 = 1
  • 右键= 2

IE8及更早的鼠标按键映射:

  • 左键 = 1
  • 中键 = 4
  • 右键= 2
于 2020-04-18T03:31:11.773 回答