鼠标指针coords上的JavaScript

时间:2011-11-11 18:30:33

标签: javascript coords

我希望在光标移动时显示光标上的坐标x,y ..

我使用波纹管脚本但它会生成一个警告框。

<script type=text/javascript>
var isIE = document.all?true:false;
if (!isIE) document.captureEvents(Event.CLICK);

document.onclick = getMousePosition;
function getMousePosition(e) {
  var _x;
  var _y;
  if (!isIE) {
    _x = e.pageX;
    _y = e.pageY;
  }
  if (isIE) {
    _x = event.clientX + document.body.scrollLeft;
    _y = event.clientY + document.body.scrollTop;
  }
  posX = _x;
  posY = _y;

  return true;
}
</script>

<body onclick=alert("X-position:&nbsp;"+posX+";&nbsp;Y-position:&nbsp;"+posY+".")>

2 个答案:

答案 0 :(得分:1)

我认为这是一个更简单的选择..

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
   $(document).mousemove(function(e){
      $('#status').html(e.pageX +', '+ e.pageY);
   }); 
})
</script>
<body>
<h2 id="status">
0, 0
</h2>
</body>
</html>

http://docs.jquery.com/Tutorials:Mouse_Position#Tracking_mouse_position

答案 1 :(得分:1)

这应该有效:

// Cursor coordinate functions
var myX, myY, xyOn, myMouseX, myMouseY;
xyOn = true;

function getXYPosition(e) {
    myMouseX = (e || event).clientX;
    myMouseY = (e || event).clientY;
    if (document.documentElement.scrollTop > 0) {
        myMouseY = myMouseY + document.documentElement.scrollTop;
    }
    if (xyOn) {
        alert("X is " + myMouseX + "\nY is " + myMouseY);
    }
}
function toggleXY() {
    xyOn = !xyOn;
    document.getElementById('xyLink').blur();
    return false;
}   

document.onmouseup = getXYPosition;

您还需要这个隐藏的超链接:

<a href="#" id="xyLink" onfocus="toggleXY();" accesskey="z"></a>

enter image description here

以下是文章:http://www.brenz.net/snippets/xy.asp