2010-07-14 47 views
2

不工作我有一個像獲取使用javascript光標位置在Firefox

function getCursorPosition(e) { 
     e = e || window.event; 
     var cursor = {x:0, y:0}; 
     if (e.pageX || e.pageY) { 
      cursor.x = e.pageX; 
      cursor.y = e.pageY; 
     } 
     else { 
      cursor.x = e.clientX + 
       (document.documentElement.scrollLeft || 
       document.body.scrollLeft) - 
       document.documentElement.clientLeft; 
      cursor.y = e.clientY + 
       (document.documentElement.scrollTop || 
       document.body.scrollTop) - 
       document.documentElement.clientTop; 
     } 
     return cursor; 
    } 

document.onmouseup = function(e){ 
    cursor = getCursorPosition(); 
    alert(cursor.x + ':' + cursor.y); 
}; 

這個代碼JavaScript警告,其中點擊光標在X和Y位置。這適用於IE 7/8,Chrome/Safari,Opera 10。但在使用Firefox 4.0 beta 1進行測試時,它不起作用。

在谷歌搜索,許多網站給了我相同的代碼。但它無法在ff 4.0b中工作

這是ff 4.0b的錯誤嗎?或任何人都可以建議我另一個跨瀏覽器光標位置腳本?

+0

......你有一個全球性的window.event對象,這就是爲什麼它在這些平臺上工作...請參閱:http://www.quirksmode.org/js/introevents.html#link10 – Roki 2010-07-14 08:03:11

回答

3

您應該將事件傳遞給getCursorPosition方法:

document.onmouseup = function(e){ 
    cursor = getCursorPosition(e); //<== added the "e" argument here 
    alert(cursor.x + ':' + cursor.y); 
}; 
1

或完全喪失getCursorPosition(),並使用極其跨瀏覽器的jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> 

<script type="text/javascript"> 
    function jQueryMain() 
    { 
     $(document).mouseup (function (evt) {alert (evt.pageX + ':' + evt.pageY);}); 
    } 

    $(document).ready (jQueryMain); 
</script> 
在IE /歌劇