我正在尝试获取滚动上的顶部偏移元素值并进行计算,以便在到达滚动上的元素时可以更改元素的类。这是函数:
handleScroll () {
const header = document.querySelector('#header');
const content = document.querySelector('#content');
const rect = header.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const headerTop = rect.top + scrollTop;
console.log(headerTop);
if (window.scrollY > headerTop) {
header.classList.add('fixed');
content.classList.add('content-margin');
} else {
header.classList.remove('fixed');
content.classList.remove('content-margin');
}
}
},
beforeMount () {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy () {
window.removeEventListener('scroll', this.handleScroll);
}
但是,在检查 console.log(headerTop);
时。在滚动时,我发现在滚动时我一直在为 headerTop 获取不同的值,只有当我停止滚动时我才能获得正确的值。我该如何解决这个问题,以便在滚动时获得正确的值?
最佳答案
getBoundingClientRect()
函数将返回一个相对于当前窗口位置的框。当元素为粘性时,它的最高值将始终为 0,或者其他固定值。
例如,这可以通过在粘性元素之前添加一个空的 div 来解决,并将其用作偏移量的引用点。
关于Javascript - 获取滚动上的元素偏移值无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090841/