我对javascript中鼠标位置的文档和视口的理解是否正确?

时间:2011-08-18 07:09:22

标签: javascript jquery html css

根据答案from a previous question,两者都指鼠标位置(x和y坐标)。

  • 相对于文档和
  • 相对于视口。

我已阅读QuirksMode上的一篇文章,但我想我可能会遗漏一些东西。我把这两个图组合起来帮助我理解。我的分析是否正确?

enter image description here

现在滚动文档250px ...

enter image description here

1 个答案:

答案 0 :(得分:3)

你的分析是正确的(那些是非常漂亮的图表!)

但是关于你的其他帖子,他们提供的信息比必要的信息要多。

您只需要了解有一个文档和视口。文档是静止的,视口随您移动(并具有滚动偏移)。

原则上,您可以将对话框窗口相对于其中任何一个放置。让我们假装对话框是一个简单的分割元素:

<body>
<button id="save">Save</button>
<div id="dialog" style="position:absolute;">Are you sure?</div>
</body>

让我们假设你想在点击时将该元素相对于你的按钮定位。您可以使用该文档:

<script>
document.getElementById("save").onclick = function(e) {
  var dialog = document.getElementById("dialog");

  dialog.style.top = e.pageY + "px";
  /*
  pageY gives the position of the mouse relative to the
  document, when this event occurred.
  */
};
</script>

或者您可以使用视口:

<script>
document.getElementById("save").onclick = function(e) {
  var dialog = document.getElementById("dialog");

  dialog.style.top = e.clientY + window.pageYOffset + "px";
  /*
  clientY gives the position of the mouse relative to
  the viewport, when this event occurred. And pageYOffset
  is the distance the user has scrolled.
  */
};
</script>

你甚至可以使用按钮本身。无论用户点击的确切位置如何,这都可以为您提供一致的位置:

<script>
document.getElementById("save").onclick = function(e) {
  var dialog = document.getElementById("dialog");

  dialog.style.top = document.getElementById("save").offsetTop + "px";
  /*
  offsetTop gives the position of the button, relative to its nearest
  positioned ancestor. If the element is deeply nested, you may need
  to do additional calculations. (jQuery's "offset" method will do this
  for you).
  */
};
</script>

要在使用jQuery的对话框类时应用最后一个方法,您可以这样做:

<script>
  $("#save").click(function(e) {
    $("#dialog").dialog({
      position: {
        my: "top",
        at: "bottom",
        of: $("#save")
      }
      /*
      See this: http://docs.jquery.com/UI/API/1.8/Position
      */
    });
  });
</script>