javascript 如何使用Javascript检查当前鼠标按钮状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12209483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check the current mouse button state Using Javascript
提问by vusan
I want the state of mouse on Down stateor on up state
我想要鼠标处于向下状态或处于向上状态
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
}
When I moved my mouse, program should show the required value of mouseState up or down on console for now
当我移动鼠标时,程序现在应该在控制台上向上或向下显示所需的 mouseState 值
回答by Christian J?rgensen
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.
您应该通过将其登录到控制台来查看“mousemove”上的事件。那里可能有一个属性显示鼠标的状态,就像 keypress 事件有一个属性告诉你是否按下了 shift 按钮。但这可能不兼容跨浏览器。
回答by xdazz
You could check the MouseEvent.which
property.
你可以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');
}
}