[removed] Check if mouse button down?

2019-01-03 05:15发布

Is there a way to detect if a mouse button is currently down in JavaScript?

I know about the "mousedown" event, but that's not what I need. Some time AFTER the mouse button is pressed, I want to be able to detect if it is still pressed down.

Is this possible?

15条回答
劳资没心,怎么记你
2楼-- · 2019-01-03 05:36

Using jQuery, the following solution handles even the "drag off the page then release case".

$(document).mousedown(function(e) {
    mouseDown = true;
}).mouseup(function(e) {
    mouseDown = false;
}).mouseleave(function(e) {
    mouseDown = false;
});

I don't know how it handles multiple mouse buttons. If there were a way to start the click outside the window, then bring the mouse into the window, then this would probably not work properly there either.

查看更多
Deceive 欺骗
3楼-- · 2019-01-03 05:37

I think the best approach to this is to keep your own record of the mouse button state, as follows:

var mouseDown = 0;
document.body.onmousedown = function() { 
    mouseDown = 1;
}
document.body.onmouseup = function() {
    mouseDown = 0;
}

and then, later in your code:

if (mouseDown == 1) {
    // the mouse is down, do what you have to do.
}
查看更多
【Aperson】
4楼-- · 2019-01-03 05:37

This is an old question, and the answers here seem to mostly advocate for using mousedown and mouseup to keep track of whether a button is pressed. But as others have pointed out, mouseup will only fire when performed within the browser, which can lead to losing track of the button state.

However, MouseEvent (now) indicates which buttons are currently pushed:

  • For all modern browsers (except Safari) use MouseEvent.buttons
  • For Safari, use MouseEvent.which (buttons will be undefined for Safari) Note: which uses different numbers from buttons for Right and Middle clicks.

When registered on document, mousemove will fire immediately as soon as the cursor reenters the browser, so if the user releases outside then the state will be updated as soon as they mouse back inside.

A simple implementation might look like:

var leftMouseButtonOnlyDown = false;

function setLeftButtonState(e) {
  leftMouseButtonOnlyDown = e.buttons === undefined 
    ? e.which === 1 
    : e.buttons === 1;
}

document.body.onmousedown = setLeftButtonState;
document.body.onmousemove = setLeftButtonState;
document.body.onmouseup = setLeftButtonState;

If more complicated scenarios are required (different buttons/multiple buttons/control keys), check out the MouseEvent docs. When/if Safari lifts its game, this should get easier.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-03 05:39

If you're working within a complex page with existing mouse event handlers, I'd recommend handling the event on capture (instead of bubble). To do this, just set the 3rd parameter of addEventListener to true.

Additionally, you may want to check for event.which to ensure you're handling actual user interaction and not mouse events, e.g. elem.dispatchEvent(new Event('mousedown')).

var isMouseDown = false;

document.addEventListener('mousedown', function(event) { 
    if ( event.which ) isMouseDown = true;
}, true);

document.addEventListener('mouseup', function(event) { 
    if ( event.which ) isMouseDown = false;
}, true);

Add the handler to document (or window) instead of document.body is important b/c it ensures that mouseup events outside of the window are still recorded.

查看更多
神经病院院长
6楼-- · 2019-01-03 05:40

Below jQuery example, when mouse is over $('.element'), color is changing depending on which mouse button is pressed.

var clicableArea = {
    init: function () {
        var self = this;
        ('.element').mouseover(function (e) {
            self.handlemouseClick(e, $(this));
        }).mousedown(function (e) {
            self.handlemouseClick(e, $(this));
        });
    },
    handlemouseClick: function (e, element) {
        if (e.buttons === 1) {//left button
            element.css('background', '#f00');
        }
        if (e.buttons === 2) { //right buttom
            element.css('background', 'none');
        }
    }
};
$(document).ready(function () {
    clicableArea.init();
});
查看更多
Juvenile、少年°
7楼-- · 2019-01-03 05:42

As said @Jack, when mouseup happens outside of browser window, we are not aware of it...

This code (almost) worked for me:

window.addEventListener('mouseup', mouseUpHandler, false);
window.addEventListener('mousedown', mouseDownHandler, false);

Unfortunately, I won't get the mouseup event in one of those cases:

  • user simultaneously presses a keyboard key and a mouse button, releases mouse button outside of browser window then releases key.
  • user presses two mouse buttons simultaneously, releases one mouse button then the other one, both outside of browser window.
查看更多
登录 后发表回答