【问题标题】:change navbar text color on scroll in react在反应中滚动更改导航栏文本颜色
【发布时间】:2021-02-28 21:25:30
【问题描述】:

你好,我是新手,我想在滚动时将导航的文本颜色更改为白色,为此我做了以下操作

useEffect(() => {
    const header = document.getElementById("myHeader");
    const navText = document.getElementById("onScroll");
    const sticky = header.offsetTop;
    const stickyNav = navText.offsetTop;

const scrollCallBack = window.addEventListener("scroll", () => {
  if (window.pageYOffset > sticky ) {
    header.classList.add("sticky");
    navText.className("navText");
    
  } else {
    header.classList.remove("sticky");
    navText.classList.remove("navText");
    
  }
});

这是我的导航代码

<div class="navbar-nav">
              <Link to="/" id="onScroll" className={`nav-item nav-link ${className}`}>
                Home
              </Link>
              <Link to="/service" id="onScroll"  className={`nav-item  nav-link ${className}`}>
                Services
              </Link>
              <a href="#" id="onScroll" className={`nav-item nav-link ${className}`}>
                About
              </a>
              <Link to="/works" id="onScroll" className={`nav-item nav-link ${className}`}>
                How it works
              </Link>
              <Link href="#" to="/covid" id="onScroll" className={`nav-item nav-link ${className}`}>
                COVID
              </Link>
            </div>

但是在 UI 上只有一个文本(主页)改变它的颜色我希望所有文本都改变颜色而不使用 jquery

这是我的css

.nav-color {
  font-family: "Source Sans Pro";
  font-weight: 600;
  text-align: left;
  color: #12356a !important;
}
.sticky {
  width: 100% !important;
  top: 0;
  z-index: 2  !important;
  background: #12356a;
  position: fixed !important;
}

【问题讨论】:

  • 你能提供 CSS 吗?
  • 确定我已经编辑了我的问题
  • 如果每个 p 元素都有相同的类,你可以只使用 document.querySelectorAll(".your_class"),然后用 .forEach() 遍历它们,或者你可以为它们创建一个 css 变量在父元素中着色,然后只需 document.getElementById("the_parent_id").setProperty("--your-css-variable-name", "white or anything")。希望对您有所帮助。
  • 你能用代码显示吗
  • 父级是导航,文本在链接标签中

标签: javascript css reactjs


【解决方案1】:

我已经用这个方法解决了,希望对别人有帮助

const [isSticky, setSticky] = useState(false);
  useEffect(() => {
    const scrollCallBack = window.addEventListener("scroll", () => {
      if (window.pageYOffset > 0 ) {
        setSticky(true)        
      } else {
        setSticky(false)       
      }
    });
    return () => {
      window.removeEventListener("scroll", scrollCallBack);
    };
  }, []);
<Link to="/"  className={`nav-item nav-link ${isSticky? "navText": null} `}>

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多