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>

当前回答

我认为他只想知道光标的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>

其他回答

只是一个简化版的@ 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>
onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}

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

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

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


    }, );

知道更多

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

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

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