Javascript onMouseMove 获取鼠标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3011418/
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-23 02:54:38  来源:igfitidea点击:

onMouseMove get mouse position

javascriptpositionmousedom-eventsonmousemove

提问by Andrew Chang

In Javascript, within the Javascript event handler for onMouseMove how do I get the mouse position in x, y coordinates relative to the top of the page?

在 Javascript 中,在 onMouseMove 的 Javascript 事件处理程序中,如何获取相对于页面顶部的 x、y 坐标中的鼠标位置?

回答by TheVillageIdiot

if you can use jQuery, then thiswill help:

如果您可以使用 jQuery,那么将有所帮助:

<div id="divA" style="width:100px;height:100px;clear:both;"></div>
<span></span><span></span>
<script>
    $("#divA").mousemove(function(e){
      var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
      var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
      $("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
      $("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
    });

</script>

here is pure javascript only example:

这是纯javascript唯一示例:

var tempX = 0;
  var tempY = 0;

  function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
      tempX = event.clientX + document.body.scrollLeft;
      tempY = event.clientY + document.body.scrollTop;
    }
    else {  // grab the x-y pos.s if browser is NS
      tempX = e.pageX;
      tempY = e.pageY;
    }  

    if (tempX < 0){tempX = 0;}
    if (tempY < 0){tempY = 0;}  

    document.Show.MouseX.value = tempX;//MouseX is textbox
    document.Show.MouseY.value = tempY;//MouseY is textbox

    return true;
  }

回答by Sayanjyoti Das

This is tried and works in all browsers:

这在所有浏览器中均已尝试并有效:

function getMousePos(e) {
    return {x:e.clientX,y:e.clientY};
}

Now you can use it in an event like this:

现在您可以在这样的事件中使用它:

document.onmousemove=function(e) {
    var mousecoords = getMousePos(e);
    alert(mousecoords.x);alert(mousecoords.y);
};

NOTE:The above function will return the mouse co-ordinates relative to the viewport, which is not affected by scroll. If you want to get co-ordinates including scroll, then use the below function.

注意:上述函数将返回相对于视口的鼠标坐标,不受滚动影响。如果您想获得包括滚动在内的坐标,请使用以下功能。

function getMousePos(e) {
    return {
        x: e.clientX + document.body.scrollLeft,
        y: e.clientY + document.body.scrollTop
    };
}

回答by MuffinTheMan

It might be a bit overkill to use d3.jsjust for finding mouse coordinates, but they have a very useful function called d3.mouse(*container*). Below is an example of doing what you want to do:

仅使用d3.js来查找鼠标坐标可能有点矫枉过正,但它们有一个非常有用的函数,称为d3.mouse(*container*). 下面是一个做你想做的事情的例子:

var coordinates = [0,0];
d3.select('html') // Selects the 'html' element
  .on('mousemove', function()
    {
      coordinates = d3.mouse(this); // Gets the mouse coordinates with respect to
                                    // the top of the page (because I selected
                                    // 'html')
    });

In the above case, the x-coordinate would be coordinates[0], and the y-coordinate would be coordinates[1]. This is extremely handy, because you can get the mouse coordinates with respect to any container you want to by exchanging 'html'with the tag (e.g. 'body'), class name (e.g. '.class_name'), or id (e.g. '#element_id').

在上述情况下,x 坐标将为coordinates[0],y 坐标将为coordinates[1]。这非常方便,因为您可以通过'html'与标记(例如'body')、类名(例如'.class_name')或 id(例如'#element_id')交换来获取与您想要的任何容器相关的鼠标坐标。

回答by kennebec

Especially with mousemove events, that fire fast and furious, its good to pare down the handlers before you use them-

特别是对于 mousemove 事件,它会快速而激烈地触发,在使用它们之前减少处理程序是很好的 -

var whereAt= (function(){
    if(window.pageXOffset!= undefined){
        return function(ev){
            return [ev.clientX+window.pageXOffset,
            ev.clientY+window.pageYOffset];
        }
    }
    else return function(){
        var ev= window.event,
        d= document.documentElement, b= document.body;
        return [ev.clientX+d.scrollLeft+ b.scrollLeft,
        ev.clientY+d.scrollTop+ b.scrollTop];
    }
})()

document.ondblclick=function(e){alert(whereAt(e))};

document.ondblclick=function(e){alert(whereAt(e))};