我创建了一个 React 组件 here我试图让标题在滚动过去后变得固定。在那种情况下,一切都按预期工作,但在我滚动到元素高度之后,它会不断地打开和关闭类。
这是滚动函数:
handleScroll: function(event) {
// Save the element we're wanting to scroll
var el = document.querySelector("#target");
// If we've scrolled past the height of the element, add a class
if (el.getBoundingClientRect().bottom <= 0) {
console.log(el.getBoundingClientRect().bottom + " bottom");
this.setState({
headerIsActive: true
});
// If we've scrolled back up to the top of the container, remove the class
} else if (el.getBoundingClientRect().top <= 0) {
console.log(el.getBoundingClientRect().top <= 0 + " top");
this.setState({
headerIsActive: false
});
}
},
有人可以告诉我我做错了什么吗?或者为我指出正确的方向?
谢谢
最佳答案
通过检测 window.scrollY 位置何时为 0 来修复,如下所示:
handleScroll: function(event) {
// Save the element we're wanting to scroll
var el = document.querySelector("#target");
var pageY = window.scrollY
// If we've scrolled past the height of the element, add a class
if (el.getBoundingClientRect().bottom <= 0) {
console.log(el.getBoundingClientRect().bottom + " bottom");
this.setState({
headerIsActive: true
});
// If we've scrolled back up to the top of the container, remove the class
} else if (pageY == 0) {
console.log("at top");
this.setState({
headerIsActive: false
});
}
},
关于javascript - React JS 粘性导航 onScroll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43615719/