2014-07-14 118 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