我想检测鼠标移动事件中鼠标右键还是左键是按下的

I want to detect whether the right or left mouse button is down during a mousemove event

本文关键字:鼠标 右键 检测 移动 事件      更新时间:2023-09-26

我正在使用HTML5,想知道在鼠标移动过程中是按住鼠标右键还是按住鼠标左键。鼠标右键有事件。按钮=2表示鼠标右键。左侧按钮有事件。按钮=0。在鼠标移动过程中,event.button始终为0。我提供了一些示例代码。我做错了什么?

<!DOCTYPE html>
<html lang="en">
<head>
<title>demo on detecting mouse buttons</title>
<meta charset="utf-8"/>
<style>
#mycanvas{ border-style:solid; width:400px; height:400px; border-width:2px;}
</style>

<script type="text/javascript">
function detectDown(event)
{
var string = "Mouse Down, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,0,300,20);
context.fillText(string,0,10);
}
function detectMove(event)
{
var string = "Mouse Move, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,30,300,20);
context.fillText(string,0,40);
}
function detectUp(event)
{
var string = "Mouse Up, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,60,300,20);
context.fillText(string,0,70);
}
</script>
</head>
<!-- -->
<body>
<canvas id="mycanvas"onmousedown="detectDown(event)" onmouseup="detectUp(event)" onmousemove="detectMove(event)" >
</canvas>
</body>
</html>

鼠标移动事件必然与按钮无关。它报告鼠标移动,无论是否按下按钮。您需要在mousedown上创建一个标志来跟踪哪个按钮被按下;在CCD_ 2上复位。

实际上,您可以:

document.body.addEventListener('mousemove', e => console.log(`mousedown: ${(e.buttons | e.button) === 1} when mousemove`));
html, body {
  height: 100%;
}
div {
  border: 2px dashed #a10000;
  height: 100%;
  text-align: center;
}
<div>mousemove here</div>

注意:当您想运行IE8下面的代码时,请使用attachEvent绑定mousemove