How to detect middle mouse button click?

2020-02-05 04:06发布

All of the questions I've seen on how to detect a middle mouse click in JavaScript are related to jQuery, but I'm wondering how I can detect middle mouse button clicks with regular JavaScript. I tried using onClick(), but it only appears to work for the left mouse button.

Is there a JavaScript function that can detect both left and middle mouse button clicks or, if not, that can detect middle mouse button clicks?

The reason I ask is that I want to make a function call when links are clicked, irregardless of whether the left or middle mouse button was used.

标签: javascript
4条回答
家丑人穷心不美
2楼-- · 2020-02-05 04:35

onclick is not tied to a mouse, but more on the target element itself.

Here's how to detect whether an element is middle clicked:

document.body.onclick = function (e) {
  if (e && (e.which == 2 || e.button == 4 )) {
    console.log('middleclicked')
  }
}
查看更多
Rolldiameter
3楼-- · 2020-02-05 04:39

The code below could help you. It can detect which mouse button the user clicked. e.which == 2 is for the middle button.

<script type="text/javascript">

function detect_button(e){  
    e = e || window.event;

    if (e.which == null){
        button = (e.button < 2) ? 'left' : ((e.button == 4) ? 'middle' : 'right');
    }
    else{
        button = (e.which < 2) ? 'left' : ((e.which == 2) ? 'middle' : 'right');
    }

    alert(button);
}

</script>
查看更多
爷、活的狠高调
4楼-- · 2020-02-05 04:42

You have to use stuff that's already built into the DOM and Javascript engines and then put in cases where browsers differ (this is why jQuery is normally used).

document.getElementById("myBtn").onclick = function(event) {
    event = event || window.event

    // Now event is the event object in all browsers.

    // Note: event.target - the reference to clicked element. IE uses event.srcElement
    // In W3C there is a button property which works same in all browsers except IE:
    // 0 - left button, 1 - middle button, 2 - right button
    // For IE, left button = button & 1 (the 1st bit) is set to 1
    // right button = button & 2 (the 2nd bit) is 1
    // and middle button = button & 4 (the 3rd bit)
    var left = event.button == 0 || 1 == event.button&1;
    var middle = event.button == 1 || 1 == event.button&2;
    var right = event.button == 2 || 1 == event.button&3;

    // Put your code here
}
查看更多
手持菜刀,她持情操
5楼-- · 2020-02-05 04:57

You'll have to detect the event 2

event = event || window.event; //make sure to pass the event into the function
if (event.which == 2) {
    //do code..
}
查看更多
登录 后发表回答