滚动时,我想根据ID更改颜色Links。我怎样才能做到这一点?
例:
<div>
<nav>
<div className="bg-mainColor h-16 flex justify-between">
<div className="text-white">Navbar</div>
<div>
<Link to="/" className="text-white">
Home
</Link>
<Link to="#first" className="text-white">
Features
</Link>
<a href="#" className="text-white">
Courses
</a>
</div>
</div>
</nav>
<div className="min-h-screen" id="feature">
Features
</div>
<div className="min-h-screen" id="course">
Courses
</div>
</div>
查看此图片以进一步了解我
最佳答案
您必须在链接中添加一个ID并在componentDidMount上添加一个事件侦听器:
componentDidMount() {
document.addEventListener('scroll' , this.handleScroll)
}
而您的
handleScroll
就像:handleScroll = (event) => {
//handle your event base on scroll in pixels or what ever for example :
if(window.scrollY > 100) {
let aEl = document.getElementById('YOUR_LINK_ID');
aEl.setAttribute("style" , "color : red")
}
}
并且不要忘记在
removeEventListener
上使用ComponentWillUnMount
:componentWillUnMount() {
document.removeEventListener('scroll',this.handleScroll);
}
关于javascript - 在React或Gatsby中滚动时如何更改链接导航栏的颜色?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60235809/