Javascript 查找 HTML 元素和浏览器(或窗口)边之间的距离

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4601852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:12:21  来源:igfitidea点击:

Find the distance between HTML element and browser (or window) sides

javascriptjqueryhtmlpositiondistance

提问by Kai

How to find the distance in pixels between html element and one of the browser (or window) sides (left or top) using jQuery?

如何使用 jQuery 查找 html 元素与浏览器(或窗口)一侧(左侧或顶部)之间的像素距离?

采纳答案by T.J. Crowder

You can use the offsetfunction for that. It gives you the element's position relative to the (left,top) of the document:

您可以offset为此使用该功能。它为您提供元素相对于文档(左,上)的位置:

var offset = $("#target").offset();
display("span is at " + offset.left + "," + offset.top + 
  " of document");

Live exampleOn my browser, that example says that the span we've targeted is at 157,47 (left,top) of the document. This is because I've applied a big padding value to the bodyelement, and used a span with a spacer above it and some text in front of it.

实时示例在我的浏览器上,该示例表明我们的目标跨度位于文档的 157,47(左、上)。这是因为我对body元素应用了一个很大的填充值,并使用了一个跨度,它上面有一个间隔,它前面有一些文本。

Here's a second exampleshowing a paragraph at the absolute left,top of the document, showing 0,0 as its position (and also showing a span later on that's offset from both the left and top, 129,19 on my browser).

这是第二个示例,显示文档顶部绝对左侧的一个段落,将 0,0 显示为它的位置(并且稍后还会显示一个跨度,该跨度与左侧和顶部的偏移量,在我的浏览器上为 129,19)。

回答by Salman A

jQuery.offsetneeds to be combined with scrollTopand scrollLeftas shown in this diagram:

jQuery.offset需要结合scrollTopscrollLeft如下图所示:

viewport scroll and element offset

视口滚动和元素偏移

Demo:

演示:

function getViewportOffset($e) {
  var $window = $(window),
    scrollLeft = $window.scrollLeft(),
    scrollTop = $window.scrollTop(),
    offset = $e.offset();
  return {
    left: offset.left - scrollLeft,
    top: offset.top - scrollTop
  };
}
$(window).on("load scroll resize", function() {
  var viewportOffset = getViewportOffset($("#element"));
  $("#log").text("left: " + viewportOffset.left + ", top: " + viewportOffset.top);
});
body { margin: 0; padding: 0; width: 1600px; height: 2048px; background-color: #CCCCCC; }
#element { width: 384px; height: 384px; margin-top: 1088px; margin-left: 768px; background-color: #99CCFF; }
#log { position: fixed; left: 0; top: 0; font: medium monospace; background-color: #EEE8AA; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- scroll right and bottom to locate the blue square -->
<div id="element"></div>
<div id="log"></div>