我想在mousemove事件期间检测鼠标右键或左键是否按下

时间:2011-10-27 22:58:08

标签: javascript html5 mousemove

我正在使用HTML5,想知道在鼠标移动过程中是否按下了鼠标右键或鼠标左键。右键有event.button = 2表示右键。左键有event.button = 0.在mousemove期间,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>

1 个答案:

答案 0 :(得分:4)

鼠标移动事件必然与按钮无关。无论是否按下按钮,它都会报告鼠标移动。您需要在mousedown上创建一个标记,以跟踪哪个按钮已关闭;在mouseup上重置它。

相关问题