【问题标题】:Mouse Event Troubles in JavaScriptJavaScript 中的鼠标事件问题
【发布时间】:2014-07-14 04:40:04
【问题描述】:

我刚开始学习 JavaScript,我正在尝试创建一个执行以下步骤的函数。

  1. 记录用户单击并按住的位置的 x 坐标(onmousedown(?),而不是 onclick)。
  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>

非常感谢任何关于任何事情的反馈/帮助/提示!

【问题讨论】:

    标签: javascript drag-and-drop mouseevent mouse


    【解决方案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");
    
    }
    

    【讨论】:

    • 谢谢!这正是我所需要的,而且你很快!非常感谢!