Javascript 获取相对于视口顶部的元素位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36175336/
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
Get an element position relative to the top of the viewport
提问by dzimi
I need to get the top position of an element relative to the top of the viewport, not the whole document.
我需要获取元素相对于视口顶部的顶部位置,而不是整个文档。
I tried offset().top;
which returns the top position relative to the document, and I tried scrollTop()
which always returns 0
regardless of the element's visibility in the viewport.
我尝试offset().top;
返回相对于文档的顶部位置,我尝试无论元素在视口中的可见性如何scrollTop()
始终返回0
。
回答by Mosh Feu
You can calculate it using
您可以使用计算它
$('#element').offset().top - $(window).scrollTop()
Working example
工作示例
function get(){
$('#output').html($('#element').offset().top - $(window).scrollTop());
}
get();
$(window).scroll(get);
#element {
width:100px;
height:100px;
background:red;
}
#output {
position:fixed;
background:#000;
color:#fff;
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="element"></div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
回答by nikk wong
For those looking for a non-jquery solution:
对于那些寻找非 jquery 解决方案的人:
let el = /* get your el */
let top = el.getBoundingClientRect().top +
el.ownerDocument.defaultView.pageYOffset