3

What is the best way to capture a left AND right mouse click in javascript? I'm not using jQuery (it's next on my to-learn list), just javascript for now. Basically, I want to do something like

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

The only thing I could find on stackoverflow was: How to distinguish between left and right mouse click with jQuery

How should I capture the double-button click? Can i check if the opposite button is also clicked during the R and L button routines?

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

両方のブール値が true の場合、マウスの右ボタンと左ボタンの両方がクリックされています。

于 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 に答える