【发布时间】:2014-07-14 04:40:04
【问题描述】:
我刚开始学习 JavaScript,我正在尝试创建一个执行以下步骤的函数。
- 记录用户单击并按住的位置的 x 坐标(onmousedown(?),而不是 onclick)。
- 然后,当鼠标仍被按下时,鼠标在 x 方向上每移动 ±100 个单位,我希望发生一个动作(对于这个问题并不重要,但例如,会出现一个弹出窗口)。
- 当用户释放鼠标 (onmouseup(?)) 时,该函数停止跟踪用户的鼠标位置并且操作停止(如果如示例中那样,不再弹出弹出窗口)
- 如果用户再次单击,请重复步骤 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>
非常感谢任何关于任何事情的反馈/帮助/提示!
【问题讨论】:
标签: javascript drag-and-drop mouseevent mouse