在React或Gatsby中滚动时如何更改链接导航栏的颜色? [英] How to change link Navbar color while scrolling in React or Gatsby?
本文介绍了在React或Gatsby中滚动时如何更改链接导航栏的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在滚动时,我想根据ID更改颜色链接.我该怎么办?
While scrolling, I want to change the color Links depending on Id. how can i do that?
示例:
<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>
查看此图片以了解我的更多信息
Check this picture to understand me more
推荐答案
您必须在链接中添加一个ID,并在componentDidMount上添加一个事件侦听器:
you must add an Id to your link and add an event listener on your 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")
}
}
并且不要忘记ComponentWillUnMount
上的removeEventListener
:
componentWillUnMount() {
document.removeEventListener('scroll',this.handleScroll);
}
这篇关于在React或Gatsby中滚动时如何更改链接导航栏的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文