[英]React.js Scroll Threshold for Revealing Navigation
Using React.js, another dev wrote this code to toggle the appearance of a navigation element called ArticleNav
. 另一个开发人员使用React.js编写了这段代码,以切换名为
ArticleNav
的导航元素的外观。 It reveals itself as your scrolling down but hides itself when you scroll back up. 向下滚动时会显示自身,而向上滚动时会隐藏自身。
onScroll: function () {
var mainColumn = document.getElementsByClassName('main-column')[0];
var firstTextElement = mainColumn.querySelector('.dek');
if (!firstTextElement) {
firstTextElement = mainColumn.querySelector('.body-text');
}
if (window.scrollY >= firstTextElement.offsetTop) {
if (!this.state.hideForArticleNav) {
this.setState({hideForArticleNav: true});
}
} else {
if (this.state.hideForArticleNav) {
this.setState({hideForArticleNav: false});
}
}
}
This works great but the use of if (window.scrollY >= firstTextElement.offsetTop)
makes this jump back and forth too rapidly and I wanted to create a, let's say..., 50px threshold to confirm that the user is actually scrolling in the opposite direction. 效果很好,但是使用
if (window.scrollY >= firstTextElement.offsetTop)
会使此跳转来回太快,我想创建一个50px的阈值来确认用户确实在滚动相反的方向。
Do y'all have any recommendations on how to approach this? 你们对如何解决这个问题有什么建议吗? I am more jQuery-minded than React, so all of my normal fixes don't exactly translate here.
我比React更注重jQuery,因此我的所有常规修补程序在此处均未完全翻译。
I feel like I'm missing part of your question. 我觉得我想念你的部分问题。 Can't you simply add 50 px to the
firstTextElement.offsetTop
? 您不能简单地将50 px添加到
firstTextElement.offsetTop
吗?
window.scrollY >= firstTextElement.offsetTop + 50
It sounds like you have a good setup to determine whether the user is scrolling up or down, so instead of setting this.state.hideForArticleNav
you could set this.state.lastDirectionChangeOffset
to the current window offset when the direction changes. 听起来您的设置不错,可以确定用户是向上滚动还是向下滚动,因此可以将
this.state.lastDirectionChangeOffset
设置为当前方向,而不是设置this.state.hideForArticleNav
来代替当前窗口的偏移量。 Then you can check against that state value to see if it's +/- 50px. 然后,您可以对照该状态值检查其是否为+/- 50px。
onScroll: function () {
var mainColumn = document.getElementsByClassName('main-column')[0];
var firstTextElement = mainColumn.querySelector('.dek');
if (!firstTextElement) {
firstTextElement = mainColumn.querySelector('.body-text');
}
if (window.scrollY >= firstTextElement.offsetTop) {
if (!this.state.hideForArticleNav) {
this.setState({ lastDirectionChangeOffset: window.scrollY });
}
} else {
if (this.state.hideForArticleNav) {
this.setState({ lastDirectionChangeOffset: window.scrollY });
}
}
if (window.scrollY > this.state.lastDirectionChangeOffset + 50) {
this.setState({ hideForArticleNav: true })
} else if (window.scrollY < this.state.lastDirectionChangeOffset - 50) {
this.setState({ hideForArticleNav: false })
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.