2025-01-05 10:00:02

跟踪鼠标位置

我希望跟踪鼠标光标的位置,周期性地每t秒。因此,从本质上讲,当一个页面加载时,这个跟踪器应该开始,(比如说)每100毫秒,我应该得到posX和posY的新值,并将其打印到表单中。

我尝试了下面的代码-但值不会刷新-只有posX和posY的初始值显示在表单框中。有什么办法能让它运行起来吗?

<html>
<head>
<title> Track Mouse </title>
<script type="text/javascript">
function mouse_position()
{
    var e = window.event;

    var posX = e.clientX;
    var posY = e.clientY;

    document.Form1.posx.value = posX;
    document.Form1.posy.value = posY;

    var t = setTimeout(mouse_position,100);

}
</script>

</head>

<body onload="mouse_position()">
<form name="Form1">
POSX: <input type="text" name="posx"><br>
POSY: <input type="text" name="posy"><br>
</form>
</body>
</html>

鼠标的位置在事件对象上报告,该事件由mouemove事件的处理程序接收,您可以将该事件附加到窗口(事件气泡):

(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
    }
})();

(注意if的主体只会在旧的IE上运行。)

上面的例子在行动-它绘制点当你拖动鼠标在页面上。(在IE8, IE11, Firefox 30, Chrome 38上测试。)

如果你真的需要一个基于定时器的解决方案,你可以将它与一些状态变量结合起来:

(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
        }
    }
})();

据我所知,如果没有看到一个事件,你就无法获得鼠标位置,这是另一个Stack Overflow问题的答案似乎证实了这一点。

旁注:如果您打算每100毫秒(10次/秒)执行某项操作,请尽量限制在该函数中执行的实际处理。这对浏览器来说工作量很大,尤其是老版本的微软浏览器。是的,在现代计算机上,它看起来并不多,但在浏览器中有很多事情要做……因此,例如,您可以跟踪您处理的最后一个位置,如果位置没有变化,您可以立即从处理程序中保释。


下面是一个基于jQuery和鼠标事件监听器(这比常规轮询要好得多)的解决方案:

$("body").mousemove(function(e) {
    document.Form1.posx.value = e.pageX;
    document.Form1.posy.value = e.pageY;
})

我认为我们想太多了,

函数mouse_position (e) { / /做东西 } <身体onmousemove = " mouse_position(事件)" > < /身体>


onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}

打开控制台(Ctrl+Shift+J),复制粘贴上面的代码,并在浏览器窗口上移动鼠标。


我认为他只想知道光标的X/Y位置,而不是为什么答案那么复杂。

// 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>


无论使用哪种浏览器,以下几行都能让我获取正确的鼠标位置。

事件。clientX - event.currentTarget.getBoundingClientRect().left 事件。clientY - event.currentTarget.getBoundingClientRect().top


基于ES6的代码

let handleMousemove = (event) => {
  console.log(`mouse position: ${event.x}:${event.y}`);
};

document.addEventListener('mousemove', handleMousemove);

如果你需要节流鼠标移动,使用这个:

let handleMousemove = (event) => {
  console.warn(`${event.x}:${event.y}\n`);
};

let throttle = (func, delay) => {
  let prev = Date.now() - delay;
  return (...args) => {
    let current = Date.now();
    if (current - prev >= delay) {
      prev = current;
      func.apply(null, args);
    }
  }
};

// let's handle mousemoving every 500ms only
document.addEventListener('mousemove', throttle(handleMousemove, 500));

这里有一个例子


如果只是想直观地跟踪鼠标移动:

<!DOCTYPE html> <html> <head> <title></title> </head> <style type="text/css"> * { margin: 0; padding: 0; } html, body { width: 100%; height: 100%; overflow: hidden; } </style> <body> <canvas></canvas> <script type="text/javascript"> var canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), beginPath = false; canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.addEventListener('mousemove', function (event) { var x = event.clientX, y = event.clientY; if (beginPath) { ctx.lineTo(x, y); ctx.stroke(); } else { ctx.beginPath(); ctx.moveTo(x, y); beginPath = true; } }, false); </script> </body> </html>


以下是两个需求的组合:每100毫秒跟踪鼠标位置:

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);
}

这将跟踪并作用于鼠标位置,但只是每周期毫秒一次。


我没有足够的声誉来发布评论回复,但采用了TJ克劳德的出色回答,并在100毫秒的计时器上完整地定义了代码。(他把一些细节留给大家想象。)

感谢OP的提问,感谢TJ的回答!你们俩都帮了大忙。代码嵌入在下面,作为isbin的镜像。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Example</title> <style> body { height: 3000px; } .dot { width: 2px; height: 2px; background-color: black; position: absolute; } </style> </head> <body> <script> (function() { "use strict"; var mousePos; document.onmousemove = handleMouseMove; setInterval(getMousePosition, 100); // setInterval repeats every X ms 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 ); } mousePos = { x: event.pageX, y: event.pageY }; } function getMousePosition() { var pos = mousePos; if (!pos) { // We haven't seen any movement yet, so don't add a duplicate dot } else { // Use pos.x and pos.y // Add a dot to follow the cursor 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>


只是一个简化版的@ tj。克劳德和@RegarBoy的回答。

在我看来,少即是多。

查看onmousemove事件以获得有关该事件的更多信息。

每次鼠标根据水平坐标和垂直坐标移动时,都会有一个新的posX和posY值。

<!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>

这是追踪鼠标位置的最简单方法

Html

<body id="mouse-position" ></body>

js

document.querySelector('#mouse-position').addEventListener('mousemove', (e) => {
        console.log("mouse move X: ", e.clientX);
        console.log("mouse move X: ", e.screenX);


    }, );

知道更多


最近,我们必须找到当前的x,y位置,以枚举光标所悬停的元素,而不依赖于z-index。我们最终只是附加了一个鼠标移动事件监听器到文档,例如,

功能findElements(e) ( var els =文档。clientX, clientY); 和els一起做酷的东西 游戏机。log (els); return; ) 文档。addEventListener (mousemove”、“findElements);


这是获取鼠标指针坐标的最短方法。 只需将元素放在光标所在的位置,在$("")内

 $("***enter you element here***").mousemove(function(event)
{
 console.clear()
  var x = event.originalEvent.screenX;
  var y = event.originalEvent.screenY;
  console.log("x : "+x)
  console.log("y : "+y)
})

这里有一个解决方案

document.onmousemove = showCoords;
function showCoords(event) {
var x = event.clientX;
var y = event.clientY;
var coords = "X coords: " + x + ", Y coords: " + y;
document.getElementById("box1").innerHTML = coords;
}

document.addEventListener('mousemove', (event) => { document.getElementById("line").style.top = event.clientY - 10 + 'px'; document.getElementById("lineY").style.left = event.clientX - 10 + 'px'; document.getElementById("pos").style.top = (event.clientY - 60) + 'px'; document.getElementById("pos").style.left = (event.clientX - 60) + 'px'; }); body { position: relative; height: auto; min-height: 100% !important; background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; } .abs { position: relative; } .lineY { display: flex; position: relative; left: 0px; background-color: black; width: 2px; height: 100vh; min-height: 100% } .line { display: flex; position: relative; background-color: black; min-height: 2px; width: 100%; } .circle { display: flex; position: absolute; left: 0px; top: 0px; } <div class='line' id="line"></div> <div class='lineY' id="lineY"></div> <svg height="100" width="100" id="pos" class="circle"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="transparent" /> </svg>


如果有人还在寻找答案,

function track(e) {
  console.log("X - ", e.pageX, " Y - ", e.pageY);
}
addEventListener("mousemove", track, false);

将此代码粘贴到控制台以查看立即的操作


[...document.querySelectorAll("*")].forEach(h => h.addEventListener("mousemove", function(event) {
    console.table({
        "mouse x": event.clientX,
        "mouse y": event.clientY
    });
}));