如何使用Javascript检查当前鼠标按钮状态

How to check the current mouse button state Using Javascript

本文关键字:鼠标 按钮 状态 何使用 Javascript 检查      更新时间:2023-09-26

我希望鼠标处于向下状态向上状态

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup   = mouseUp;
function mouseMove(ev) {
    mouseState="";
    //How can I know the state button of mouse button from here 
    if(mouseState=='down') {
        console.log('mouse down state')
    }
    if(mouseState=='up')  {
        console.log('mouse up state')
    }
}
function mouseDown(ev) {
    console.log('Down State you can now start dragging');
    //do not write any code here in this function
}
function mouseUp(ev) {
    console.log('up state you cannot drag now because you are not holding your mouse')
    //do not write any code here in this function
} 

当我移动鼠标时,程序应该在控制台上向上或向下显示所需的mouseState值

您可以检查MouseEvent.which属性。

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

您只需要为它创建一个变量。

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
}

您应该通过将"mousemove"事件记录到控制台中来查看该事件。那里可能有一个属性显示鼠标的状态,就像keypress事件有一个"告诉"您是否按下了shift按钮的属性一样。但这可能与跨浏览器不兼容。