问题
I want the state of mouse on Down state or 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
回答1:
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.
回答2:
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');
}
}
来源:https://stackoverflow.com/questions/12209483/how-to-check-the-current-mouse-button-state-using-javascript