gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:37:14 25 4
gpt4 key购买 nike

基于答案 from a previous question ,两者都指的是鼠标位置(x 和 y 坐标)。

  • 相对于文档和
  • 相对于视口(viewport)。

我已经阅读了一篇关于 QuirksMode 的文章,但是我想我可能会遗漏一些东西。我将这两个图表放在一起以帮助我理解。我的分析正确吗?

enter image description here

现在将文档滚动 250px...

enter image description here

最佳答案

您的分析是正确的(而且这些图表非常好!)

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

你只需要了解有文档和视口(viewport)。文档是静止的,视口(viewport)会随着您移动(并且有滚动偏移)。

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

<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>

或者您可以使用视口(viewport):

<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>

关于javascript - 我对 javascript 中鼠标位置的文档和视口(viewport)的理解是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7103649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com