How to check the current mouse button state Using Javascript [duplicate]

匆匆过客 提交于 2019-12-05 19:04:45

You just have to create a variable for it.

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup   = mouseUp;
var mouseState = "up";

function mouseMove(ev) {

    //How can I know the state of mouse from here 
    if(mouseState=='down') {
        console.log('mouse down state')
    }

    if (mouseState=='up')  {
        console.log('mouse up state')
    }
}

function mouseDown(ev) {
    mouseState = "down";
    console.log('Down State you can now start dragging');
    //do not write any code here in this function
}

function mouseUp(ev) {
    mouseState = "up";
    console.log('up state you cannot drag now because you are not holding your mouse')
    //do not write any code here in this function
}

You should have a look at the event on "mousemove", by logging it into the console. There might be a property there that shows that state of the mouse, just like the keypress event has a property which tells you if the shift button is pressed. But that might not be cross browser compatible.

You could check the MouseEvent.which property.

function mouseMove(ev) {
    if(ev.which==1) {
        console.log('mouse down state with left click');
    } else if(ev.which==3)  {
        console.log('mouse down state with right click');
    } else {
        console.log('mouse update');
    } 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!