无法获取位置:固定的元素上的坐标

时间:2011-03-29 17:27:00

标签: javascript jquery

我正在尝试在图像上获得点击 x和y位置,并希望图像保持在向上/向下滚动的相同位置。问题是脚本/浏览器不知道该怎么做,因为图像的位置如果修复了。我猜我是否可以将它改为绝对位置并在我去的时候监视它但滚动的东西并不是那么顺利。任何想法的家伙?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <style type="text/css">
    #AutoScrollDotNetImage
    {
     width: 500px;
      position: fixed;
      clear: both;*/
    }
    body
    {
      background-color: Silver;
    }
  </style>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#DotNetImage").click(function (e) {
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
          $('#posx').html('<p>X Coordinate: ' + x + ', Y Coordinate: ' + y + "</p><p>e.pageX: " + e.pageX + "e.pageY: " + e.pageY + "</p><p>" + "this.offsetLeft: " + this.offsetLeft + "this.offsetTop: " + this.offsetTop + "</p>");
      });
    });
  </script>
</head>
<body>
  <table width="100%">
    <tr valign="top">
      <td style="background-color: Gray">
        <div id="AutoScrollDotNetImage">
        <p> ELEMENT COORDINATE</p>
          <div id="posx">
           <p> scroll and click on google image</p>
        </div>
          <img id="DotNetImage" alt="No change" src="http://www.google.com/images/logos/ps_logo2.png" />
    </div>
      </td>
      <td>
        <div style="clear: both; height: 5000px;">
          &nbsp;
        </div>
      </td>
    </tr>
  </table>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要在位置等式中加入$('body').scrollLeft()$('body').scrollTop()

$("#DotNetImage").click(function(e) {
    var x = e.pageX - $('body').scrollLeft() - this.offsetLeft;
    var y = e.pageY - $('body').scrollTop() - this.offsetTop;
    // ...etc
}

See updated fiddle →