Javascript - 跟踪鼠标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7790725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:36:22  来源:igfitidea点击:

Javascript - Track mouse position

javascript

提问by Hari

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 ms, I should get the new value of posX and posY and print it out in the form.

我希望每隔 t 毫秒定期跟踪鼠标光标的位置。所以基本上,当一个页面加载时——这个跟踪器应该启动,并且(比如说)每 100 毫秒,我应该获取 posX 和 posY 的新值并在表单中打印出来。

I tried the following code - but the values do not get refreshed - only the initial values of posX and posY show up in the form boxes. Any ideas on how I can get this up and running ?

我尝试了以下代码 - 但值没有刷新 - 只有 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>

回答by T.J. Crowder

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

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

(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 ifwill only run on old IE.)

(请注意,它的主体if只能在旧的 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.)

上面的示例- 当您将鼠标拖到页面上时,它会绘制点。(在 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 questionseems to confirm.

据我所知,您在没有看到事件的情况下无法获得鼠标位置,这个对另一个 Stack Overflow 问题的回答似乎证实了这一点

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.

旁注:如果您打算每 100 毫秒(10 次/秒)做某事,请尽量保持您在该函数中所做的实际处理非常非常有限。这对浏览器来说是很多工作,尤其是较旧的 Microsoft 浏览器。是的,在现代计算机上它看起来并不多,但是浏览器中发生了很多事情......因此,例如,您可能会跟踪您处理的最后一个位置并立即从处理程序中退出,如果该位置没有“ t变了。

回答by solendil

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

这是一个解决方案,基于 jQuery 和主体上的鼠标事件侦听器(远好于常规轮询):

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

回答by RegarBoy

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

Open your console (Ctrl+Shift+J), copy-paste the code above and move your mouse on browser window.

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

回答by dGRAMOP

I believe that we are overthinking this,

我相信我们想多了,

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

回答by Murtaza

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

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

回答by oboshto

ES6 based code:

基于 ES6 的代码:

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

document.addEventListener('mousemove', handleMousemove);

If you need throttling for mousemoving, use this:

如果您需要限制鼠标移动,请使用以下命令:

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

here is example

这是例子

回答by luistar15

If just want to track the mouse movement visually:

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

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

回答by Sai Ganesh Pittala

Irrespective of the browser, below lines worked for me to fetch correct mouse position.

无论浏览器如何,以下几行都对我有用以获取正确的鼠标位置。

event.clientX - event.currentTarget.getBoundingClientRect().left event.clientY - event.currentTarget.getBoundingClientRect().top

event.clientX - event.currentTarget.getBoundingClientRect().left event.clientY - event.currentTarget.getBoundingClientRect().top

回答by Kris with a K

I don't have enough reputation to post a comment reply, but took TJ Crowder's excellent answerand fully defined the code on a 100ms timer. (He left some details to the imagination.)

我没有足够的声誉来发表评论回复,但采用了 TJ Crowder 的出色回答在 100ms 计时器上完全定义了代码。(他留下了一些想象的细节。)

Thanks OP for the question, and TJ for the answer! You're both a great help. Code is embedded below as a mirror of isbin.

感谢 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>

回答by Jonas

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

只是@TJ Crowder@RegarBoy答案的简化版本。

Less is more in my opinion.

在我看来,少即是多。

Check out onmousemove eventfor more info about the event.

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

Image mouse tracker

图像鼠标跟踪器

There's a new value of posXand posYevery time the mouse moves according to the horizontal and vertical coordinates.

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

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