2012-02-01 17 views
0

私はdivでマウス座標を取得するために小さな関数を作成しましたが、何とか動作していません。私は機能を徹底的にチェックしたが、バグを見つけられなかった。javascriptのマウス座標ですか?

<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title></title> 
    <script type="text/javascript"> 
    function SetValues() 
    { 
    var s = "X:" + window.event.clientX + " Y:" + window.event.clientY ; 
    document.getElementById('divCoord').innerHTML = s; 
    } 
    </script> 
    </head> 
    <body onmousemove=SetValues()> 
    <div id="divCoord"></div> 
    </body> 
    </html> 

答えて

0

window.event.clientX & window.event.clientY

試してみてください。

$(document).ready(function(e) { 
    $('body').live('mousemove', function(e) { 
     alert('x: ' + window.event.clientX + ', y: ' + window.event.clientY); 
    }) 
}); 
1

window.eventプロパティは、Internet Explorerで、唯一私が考えるいくつかのバージョンでは唯一の存在です。実際、あなたがしようとしている操作全体にはかなり高度なクロスブラウザコーディングが必要です。

jQueryなどのイベントを正規化するJavaScriptフレームワークの使用を検討することをお勧めします。

のjQueryを使用して

、これはすべてのブラウザで動作します:

$(document).mousemove(function(e) { 
    $('#divCoord').html('X:' + e.pageX + ' Y:' + e.pageY); 
}); 
1

は、このコードを試してみてください。 JS

document.onmousemove = getMouseXY; 
    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; 
    } 

HTML

X <input type="text" name="MouseX" value="0" size="4"><br> 
Y <input type="text" name="MouseY" value="0" size="4"><br> 

Source

関連する問題