【问题标题】:Changing color of Navbar react js改变导航栏反应js的颜色
【发布时间】:2022-01-09 20:27:39
【问题描述】:

我正在尝试使用此代码更改导航栏的颜色。

  const [navbarColor, setNavbarColor] = useState("navbar-transparent");
  const [collapseOpen, setCollapseOpen] = useState(false);
  useEffect(() => {
    const updateNavbarColor = () => {
      if (
        document.documentElement.scrollTop > 399 ||
        document.body.scrollTop > 399
      ) {
         setNavbarColor("");
      } else if (
        document.documentElement.scrollTop < 400 ||
        document.body.scrollTop < 400
      ) {
        setNavbarColor("navbar-transparent");
      }
    };
    window.addEventListener("scroll", updateNavbarColor);
    return function cleanup() {
      window.removeEventListener("scroll", updateNavbarColor);
    };
  });

这就是我制作导航栏的方式

      <Navbar className={"fixed-top " + navbarColor} expand="lg" color="info">

但是,当我向下滚动网页时,虽然代码看起来不错,但网页崩溃了。

【问题讨论】:

    标签: javascript html css reactjs vertical-scrolling


    【解决方案1】:

    试试这个逻辑代码。

    import { useEffect } from 'react'
    
    
    export function useObservableAnimations() {
    
      const animationOnScroll = () => {
     const target = document.querySelectorAll('[data-animation')
        target.forEach(element => {
          if (element.getBoundingClientRect().top < window.innerHeight) {
            element.classList.add('animation-start')
            return
          }
          element.classList.remove('animation-start')
        })
      }
      useEffect(() => {
        window.addEventListener('scroll', animationOnScroll)
      }, [])
    }
    

    【讨论】:

    • 页面现在没有崩溃,但是颜色没有变化
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多