繁体   English   中英

在 React 或 Gatsby 中滚动时如何更改链接导航栏颜色?

[英]How to change link Navbar color while scrolling in React or Gatsby?

滚动时,我想根据 Id 更改颜色链接。 我怎样才能做到这一点?

例子:

     <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")

  } 
}

并且不要忘记在ComponentWillUnMountremoveEventListener

componentWillUnMount() {
  document.removeEventListener('scroll',this.handleScroll);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM