20

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

4

4 回答 4

28

如果您可以使用 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>

这是纯 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;
  }
于 2010-06-10T03:34:32.357 回答
8

这在所有浏览器中都经过尝试和工作:

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

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

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

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

function getMousePos(e) {
    return {
        x: e.clientX + document.body.scrollLeft,
        y: e.clientY + document.body.scrollTop
    };
}
于 2016-11-25T16:26:14.173 回答
6

仅使用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')
    });

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

于 2013-02-27T22:03:16.537 回答
4

尤其是 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))};

于 2010-06-10T04:46:18.947 回答