capture mouse position on setInterval() in Javascript

后端 未结 2 1201
小鲜肉
小鲜肉 2021-01-05 07:09

I have a function in javascript that moves one div depending on the mouse position. This function is set on a setInterval() function and executed every second. I need to cap

2条回答
  •  一生所求
    2021-01-05 07:40

    The only time that you can access the event object is during the execution of an event handler. So what you need to do is create an OnMouseMove event on the document and store the mouse coordinates in a globally accessible object. You can then access these values from anywhere else in your script to determine the mouse position.

    Here is an example (you're not using jQuery, so this is straight DOM code):

    document.onmousemove = function(e) {
        var event = e || window.event;
        window.mouseX = event.clientX;
        window.mouseY = event.clientY;
    }
    
    function mousemov() {
        document.getElementById("myDiv").style.left = window.mouseX;
    }
    
    window.onload = function() {
        setInterval(mousemov, 1000);
    }
    

    I should make the note that clientX and clientY don't take scrolling into account. You'll need to retrieve the scrolling offsets and apply them to the returned values.

提交回复
热议问题