简体   繁体   English

JavaScript setTimeout()无法触发自身

[英]JavaScript setTimeout() can't trigger itself

How can a function, which is triggered by another function, get the mouse's position? 由另一个功能触发的一个功能如何获取鼠标的位置? Here's my code: 这是我的代码:

function myFunction(e){
    setTimeout(function(){
        if(isMouseDown == true){
            mouseX = e.clientX;
            mouseY = e.clientY;
            document.getElementById('myElement').innerHTML = mouseX + ' , ' + mouseY;
            myFunction(event);
        } else {}
    }, 100);
}

What this does is to display the coordinates when clicked. 这样做是在单击时显示坐标。 I need it to display them every 100ms if isMouseDown == true . 如果isMouseDown == true我需要每100毫秒显示一次。

Thanks 谢谢

There is no way in Javascript for a random Javascript function to get the mouse position. Javascript中没有办法让随机Javascript函数获取鼠标位置。 The current mouse position only comes from an event object for a mouse-related event. 当前鼠标位置仅来自与鼠标相关的事件的事件对象。 So, if you want to keep track of the mouse position, then you can register an event handler for the mousemove event and for mousedown and mouseup to keep track of the button state. 因此,如果要跟踪鼠标位置,则可以为mousemove事件以及mousedownmouseup注册事件处理程序,以跟踪按钮状态。

If you only want to display the mouse position, ever 100ms, then you can set a timer so that it is only displayed that often, but you will need to keep track of the current mouse position in a mousemove event handler. 如果您只想显示鼠标位置(每100毫秒一次),则可以设置一个计时器,使其仅经常显示一次,但是您需要在mousemove事件处理程序中跟踪当前鼠标位置。

Here's a simple code example: 这是一个简单的代码示例:

 var lastMouseX = 0, lastMouseY = 0; document.addEventListener("mousemove", function(e) { lastMouseX = e.clientX; lastMouseY = e.clientY; }); var mouseTimer; document.addEventListener("mousedown", function() { if (!mouseTimer) { mouseTimer = setInterval(function() { document.getElementById("x").innerHTML = lastMouseX; document.getElementById("y").innerHTML = lastMouseY; }, 100); } }); document.addEventListener("mouseup", function() { clearInterval(mouseTimer); mouseTimer = null; }); 
 <div id="x"></div> <div id="y"></div> 

It's a bit fuzzy what you're trying to achieve, however you're not going to get a periodic event if you're using setTimeout() . 您想要实现的目标有点模糊,但是如果您使用setTimeout() ,则不会得到定期事件。 It sounds like you're looking for setInterval() . 听起来您正在寻找setInterval() See the below example: 请参见以下示例:

  var mouseX = 0; var mouseY = 0; var isMouseDown = true; document.onmousemove = function(e){ mouseX = e.pageX; mouseY = e.pageY; } setInterval("myFunction()", 100); function myFunction(){ if(isMouseDown) { document.getElementById('myElement').innerHTML = mouseX + ' , ' + mouseY; } } 
 <div id="myElement"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM