从页面顶部获取项目偏移量 [英] Get item offset from the top of page
本文介绍了从页面顶部获取项目偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取div的顶部偏移量,并且我有以下代码在页面滚动时运行:
I am trying to get the top offset of a div, and I have the following code that gets run when the page gets scrolled:
var $elem = document.querySelector(selector);
var elemTop = $elem.offsetTop;
console.log(elemTop);
但滚动时总是打印 0
到控制台,即使元素低于折叠。
But when I scroll it always prints 0
to the console, even though the element is below the fold.
推荐答案
var elmTop = $elem.getBoundingClientRect().top + window.scrollY;
element.getBoundingClientRect()给出视口内的位置,window.scrollY给出从视口顶部到文档顶部的距离。
element.getBoundingClientRect() gives the position within the viewport, and window.scrollY gives the distance from the top of the viewport to the top of the document.
这篇关于从页面顶部获取项目偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文