onMouseMove获取鼠标位置

And*_*ang 19 javascript mouse position onmousemove dom-events

在javascript中,在onMouseMove的javascript事件处理器中如何获得x,y中的鼠标位置相对于页面顶部的corrdinates?

The*_*iot 26

如果你可以使用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>
Run Code Online (Sandbox Code Playgroud)

这里只是纯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;
  }
Run Code Online (Sandbox Code Playgroud)


Muf*_*Man 5

使用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')
    });
Run Code Online (Sandbox Code Playgroud)

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


Say*_*Das 5

这是尝试过的,并且可以在所有浏览器中使用:

function getMousePos(e) {
    return {x:e.clientX,y:e.clientY};
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以在以下事件中使用它:

document.onmousemove=function(e) {
    var mousecoords = getMousePos(e);
    alert(mousecoords.x);alert(mousecoords.y);
};
Run Code Online (Sandbox Code Playgroud)

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

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