Javascript - Track mouse position

后端 未结 11 1241
谎友^
谎友^ 2020-11-22 03:13

I am hoping to track the position of the mouse cursor, periodically every t mseconds. So essentially, when a page loads - this tracker should start and for (say) every 100 m

相关标签:
11条回答
  • 2020-11-22 03:46

    Here’s a combination of the two requirements: track the mouse position, every 100 milliseconds:

    var period = 100,
        tracking;
    
    window.addEventListener("mousemove", function(e) {
        if (!tracking) {
            return;
        }
    
        console.log("mouse location:", e.clientX, e.clientY)
        schedule();
    });
    
    schedule();
    
    function schedule() {
        tracking = false;
    
        setTimeout(function() {
            tracking = true;
        }, period);
    }
    

    This tracks & acts on the mouse position, but only every period milliseconds.

    0 讨论(0)
  • 2020-11-22 03:51

    Just a simplified version of @T.J. Crowder and @RegarBoy's answers.

    Less is more in my opinion.

    Check out onmousemove event for more info about the event.

    There's a new value of posX and posY every time the mouse moves according to the horizontal and vertical coordinates.

    <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <title>Example Mouse Tracker</title>
          <style>    
            body {height: 3000px;}
            .dot {width: 2px;height: 2px;background-color: black;position: absolute;}
          </style>
        </head>
        <body>
        <p>Mouse tracker</p>
        <script>
        onmousemove = function(e){
            //Logging purposes
            console.log("mouse location:", e.clientX, e.clientY);
    
            //meat and potatoes of the snippet
            var pos = e;
            var dot;
            dot = document.createElement('div');
            dot.className = "dot";
            dot.style.left = pos.x + "px";
            dot.style.top = pos.y + "px";
            document.body.appendChild(dot);
        }      
        </script>
        </body>
        </html>
    
    0 讨论(0)
  • 2020-11-22 03:54

    What I think that he only wants to know the X/Y positions of cursor than why answer is that complicated.

    // Getting 'Info' div in js hands
    var info = document.getElementById('info');
    
    // Creating function that will tell the position of cursor
    // PageX and PageY will getting position values and show them in P
    function tellPos(p){
      info.innerHTML = 'Position X : ' + p.pageX + '<br />Position Y : ' + p.pageY;
    }
    addEventListener('mousemove', tellPos, false);
    * {
      padding: 0:
      margin: 0;
      /*transition: 0.2s all ease;*/
      }
    #info {
      position: absolute;
      top: 10px;
      right: 10px;
      background-color: black;
      color: white;
      padding: 25px 50px;
    }
    <!DOCTYPE html>
    <html>
      
      <body>
        <div id='info'></div>
            </body>
      </html>

    0 讨论(0)
  • 2020-11-22 03:55

    I believe that we are overthinking this,

    function mouse_position(e)
    {
    //do stuff
    }
    <body onmousemove="mouse_position(event)"></body>

    0 讨论(0)
  • 2020-11-22 03:56

    The mouse's position is reported on the event object received by a handler for the mousemove event, which you can attach to the window (the event bubbles):

    (function() {
        document.onmousemove = handleMouseMove;
        function handleMouseMove(event) {
            var eventDoc, doc, body;
    
            event = event || window.event; // IE-ism
    
            // If pageX/Y aren't available and clientX/Y are,
            // calculate pageX/Y - logic taken from jQuery.
            // (This is to support old IE)
            if (event.pageX == null && event.clientX != null) {
                eventDoc = (event.target && event.target.ownerDocument) || document;
                doc = eventDoc.documentElement;
                body = eventDoc.body;
    
                event.pageX = event.clientX +
                  (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
                  (doc && doc.clientLeft || body && body.clientLeft || 0);
                event.pageY = event.clientY +
                  (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
                  (doc && doc.clientTop  || body && body.clientTop  || 0 );
            }
    
            // Use event.pageX / event.pageY here
        }
    })();
    

    (Note that the body of that if will only run on old IE.)

    Example of the above in action - it draws dots as you drag your mouse over the page. (Tested on IE8, IE11, Firefox 30, Chrome 38.)

    If you really need a timer-based solution, you combine this with some state variables:

    (function() {
        var mousePos;
    
        document.onmousemove = handleMouseMove;
        setInterval(getMousePosition, 100); // setInterval repeats every X ms
    
        function handleMouseMove(event) {
            var dot, eventDoc, doc, body, pageX, pageY;
    
            event = event || window.event; // IE-ism
    
            // If pageX/Y aren't available and clientX/Y are,
            // calculate pageX/Y - logic taken from jQuery.
            // (This is to support old IE)
            if (event.pageX == null && event.clientX != null) {
                eventDoc = (event.target && event.target.ownerDocument) || document;
                doc = eventDoc.documentElement;
                body = eventDoc.body;
    
                event.pageX = event.clientX +
                  (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
                  (doc && doc.clientLeft || body && body.clientLeft || 0);
                event.pageY = event.clientY +
                  (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
                  (doc && doc.clientTop  || body && body.clientTop  || 0 );
            }
    
            mousePos = {
                x: event.pageX,
                y: event.pageY
            };
        }
        function getMousePosition() {
            var pos = mousePos;
            if (!pos) {
                // We haven't seen any movement yet
            }
            else {
                // Use pos.x and pos.y
            }
        }
    })();
    

    As far as I'm aware, you can't get the mouse position without having seen an event, something which this answer to another Stack Overflow question seems to confirm.

    Side note: If you're going to do something every 100ms (10 times/second), try to keep the actual processing you do in that function very, very limited. That's a lot of work for the browser, particularly older Microsoft ones. Yes, on modern computers it doesn't seem like much, but there is a lot going on in browsers... So for example, you might keep track of the last position you processed and bail from the handler immediately if the position hasn't changed.

    0 讨论(0)
  • 2020-11-22 04:02

    Here's a solution, based on jQuery and a mouse event listener (which is far better than a regular polling) on the body:

    $("body").mousemove(function(e) {
        document.Form1.posx.value = e.pageX;
        document.Form1.posy.value = e.pageY;
    })
    
    0 讨论(0)
提交回复
热议问题