简体   繁体   中英

Changing color of Navbar react js

I am trying to change the color of my navbar using this code.

  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);
    };
  });

This is how I am making navbar

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

However, when I scroll down the web page crashes, although the code looks fine.

Try this logic code.

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)
  }, [])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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