How to detect middle mouse button click?

前端 未结 4 849
旧时难觅i
旧时难觅i 2020-12-09 18:11

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 wit

4条回答
  •  佛祖请我去吃肉
    2020-12-09 18:24

    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
    }
    

提交回复
热议问题