gpt4 book ai didi

Javascript - 获取滚动上的元素偏移值无法正常工作

转载 作者:行者123 更新时间:2023-11-28 02:42:33 25 4
gpt4 key购买 nike

我正在尝试获取滚动上的顶部偏移元素值并进行计算,以便在到达滚动上的元素时可以更改元素的类。这是函数:

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/

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