2010-06-10 121 views
15

在javascript中,在onMouseMove的javascript事件處理程序中,如何獲取x,y相對於頁面頂部的鼠標位置?onMouseMove獲取鼠標位置

+0

可能重複[如何獲得jQuery的鼠標位置沒有鼠標 - 事件?](http://stackoverflow.com/questions/4517198/how-to-get-mouse-position-in-jquery-without-mouse-events) – Lucio 2014-10-12 19:56:50

回答

24

,如果你可以使用jQuery,然後this將幫助:

<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; 
    } 
+0

嗯,JS例子似乎非常類似於http:// www.codelifter.com/main/javascript/capturemouseposition1.html除非沒有方便的評論 – RozzA 2015-06-04 21:49:46

+1

'id =「#divA」'和'$(「divA」)' - 有人在寫這個時候睡着了 – RozzA 2015-06-05 21:56:26

+0

@RozzA感謝您的關注。 – TheVillageIdiot 2015-06-06 10:19:06

4

特別是隨着鼠標移動事件,火災快速和激烈,其良好的在使用它們之前減少處理程序 -

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

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

在上述情況下,x座標將是coordinates[0]和y座標將是coordinates[1]。這非常方便,因爲通過與標籤(例如'body'),類名稱(例如'.class_name')或id(例如'#element_id')交換'html',您可以獲得與您想要的任何容器相關的鼠標座標。

+0

+1,但**公平的警告**:這種方法是有點太滯後用於'onmousemove'。我的項目中已經有了d3.js,所以我嘗試了一下,但對於我的用例來說,這還不夠快。 – elrobis 2015-09-02 19:37:52

3

這是嘗試和作品在所有瀏覽器:

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

現在你可以在這樣一個事件中使用它:

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