将鼠标悬停在图像上时,如何显示带有x-y坐标的十字光标?

时间:2011-09-23 08:24:04

标签: javascript html image cursor coordinates

我在div中有一个用户可以点击的图像。

当实时悬停在该图像上时,有没有办法显示光标的坐标?我知道要显示十字光标,必须设置光标类型:cursor: crosshair - 但我怎么能显示这些坐标?

4 个答案:

答案 0 :(得分:2)

尝试:

$(function () {
    $('#hover-img')

    // show the coordinates box on mouseenter
    .bind('mouseenter', function () {
      $('#coordinates').show();
    })

    // hide it on mouseleave
    .bind('mouseleave', function () {
      $('#coordinates').hide();
    })

    // update text and position on mousemove
    .bind('mousemove', function (evt) {
      $('#coordinates').html(
        (evt.pageX - this.offsetLeft) + '/' + (evt.pageY - this.offsetTop)
      ).css({
        left: evt.pageX + 20,
        top: evt.pageY + 20
      })
    });
});

注意:请参阅» demo了解所使用的html元素。

答案 1 :(得分:0)

使用jQuery,您可以:

<script language="text/javascript">
    $('#your_image').mouseover(function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        alert("X: " + x + " Y: " + y); 
    });
</script>

答案 2 :(得分:0)

<html>
 <head>
  <script>
     function onMouseOver(Sender,e){
       var x = e.x - Sender.offsetLeft;
       var y = e.y - Sender.offsetTop;
       document.getElementById('coord').innerHTML = x+"-"+y;        
     }
  </script>
 </head>
 <body>
  <img src="image.jpg" onmousemove="onMouseOver(this,event)">
  <span id='coord'></span>
</body>
</html>

答案 3 :(得分:0)

<html>
  <head>
    <script type="text/javascript">

    function getAbsoluteOffset(htmlelement) {
      var offset={x:htmlelement.offsetLeft,y:htmlelement.offsetTop};
      while(htmlelement=htmlelement.offsetParent)
      {
        offset.x+=htmlelement.offsetLeft;
        offset.y+=htmlelement.offsetTop;
      }
      return offset;
    }
    function image_onmouseout(ev) {
      document.getElementById("mouseinfo").innerHTML="Mouse outside of image";
    }
    function image_onmousemove(ev) {
      var offset=getAbsoluteOffset(this);
      document.getElementById("mouseinfo").innerHTML=
          "Coordinates in page: (x: "+ev.clientX+",y:"+ev.clientY+")"+
          "<br/>"+
          "Coordinates in image: (x: "+(ev.clientX-offset.x)+",y:"+(ev.clientY-offset.y)+")";
    }
    </script>
  </head>
  <body>
    <div style="width:400px;height:400px;background:red;">
      <img src="image.png"
       onmouseout="image_onmouseout.call(this,event);"
       onmousemove="image_onmousemove.call(this,event);" />
    </div>
    <span id="mouseinfo">Mouse outside of image</span>
  </body>
</html>

示例:http://jsfiddle.net/HWMtc/