2011-10-27 59 views
2

我正在使用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> 
+0

您可能會發現jsfiddle.com適用於這些測試和演示。 –

回答

4

鼠標移動事件必然與按鈕無關。無論是否按下按鈕,它都會報告鼠標移動。您需要在mousedown上創建一個標誌,以跟蹤哪個按鈕處於關閉狀態;重置它在mouseup