2014-07-14 119 views
2

我剛開始學習JavaScript,並試圖創建一個執行以下步驟的函數。JavaScript中的鼠標事件故障

  1. 記錄用戶點擊並保持的位置(onmousedown(?),而不是onclick)的x座標。
  2. 然後,當鼠標仍然點擊時,鼠標在x方向上移動的每±100個單位,我想要發生一個動作(這個問題不重要,但例如彈出窗口)。
  3. 當用戶釋放鼠標(onmouseup(?))時,該功能將停止跟蹤用戶的鼠標位置並停止操作(如本例中彈出窗口不再彈出)
  4. 重複步驟1 -3如果用戶再次點擊。

這是我可憐的企圖......

<DOCTYPE! html> 
<html > 
<body onmousedown="doThing()"> 
<script type="text/javascript"> 

//global variable that tracks whether or not mouse is down or up. 
var mouseDown = 0; 

document.body.onmousedown = function() 
{ 
    ++mouseDown; 
} 
document.body.onmouseup = function() 
{ 
    --mouseDown; 
} 

//displays the state of the mouse on screen. 1 means mouse is down, 0 means mouse is up. 
function track() 
{ 
mouseState.innerHTML = mouseDown; 
} 

//when the mouse moves 100 units in either direction from the location of the initial downclick, a popup appears 
function doThing() 
{ 
    var xPos = window.event.clientX; 
    if (mouseDown==1 && ((Math.abs(xPos-window.event.clientX))>100)) 
     alert("yay"); 

} 

</script> 
<div align="center"><span id="mouseState"></span></div> 
</body> 
</html> 

任何意見/幫助不談/提示是非常感謝!

回答

1

這就是我想出:JSFiddle

//global variable that tracks whether or not mouse is down or up. 
var mouseDown = 0; 
//global variable that tracks where the mouse position when pressed 
var firstPos = 0; 
document.body.onmousedown = function(event) 
{ 
    mouseDown = 1; 
    track(); 
    firstPos = window.event.clientX; 
} 
document.body.onmouseup = function(event) 
{ 
    mouseDown = 0 
    track(); 
    firstPos = 0; 
} 
document.body.onmousemove = function() 
{ 
    if (mouseDown == 1){ 
     doThing(); 
    } 
} 
document.body.onmouseout = function() 
{ 
    //important because when you click the alert button `onmouseup` won't be triggered 
    mouseDown = 0; 
} 
//displays the state of the mouse on screen. 1 means mouse is down, 0 means mouse is up. 
function track() 
{ 
    mouseState.innerHTML = mouseDown; 
} 

//when the mouse moves 100 units in either direction from the location of the initial downclick, a popup appears 
function doThing(event) 
{ 
    if (mouseDown==1 && ((Math.abs(firstPos-window.event.clientX))>100)) 
     alert("yay"); 

} 
+0

謝謝!這正是我需要的,而且你非常快!非常感激! – jimjam