繁体   English   中英

如何使用在反应 js 中固定的 position 为 div 设置动画?

[英]How to animate a div with a position fixed in react js?

我有一个 header 组件,它在用户向下滚动后得到固定的 class:

 const [show, setShow] = React.useState(false);

  const handleShow = () => {
    if (typeof window !== "undefined") {
      if (window.pageYOffset > 120) {
        if (!show) {
          console.log("set to true");
          setShow(true);
        }
      }
      if (window.pageYOffset < 120) {
        console.log("set to false");
        setShow(false);
      }
    }
  };

  React.useEffect(() => {
    if (typeof window !== "undefined") {
      window.addEventListener("scroll", handleShow);
    }
    return () => {
      if (typeof window !== "undefined") {
        window.removeEventListener("scroll", handleShow);
      }
    };
  }, []);

return (
       <div
          className={show ? classes.fixed : ""}
          style={{
            background: bgColor,
            boxShadow: "0 0 10px #ccc",
          }}
        >
          <div className="d-flex justify-content-center">
           <div>Header</div>
          </div>
        </div>

固定 class 的 css 代码为:

.fixed {
  position: fixed;
  transition: all 0.3s;
  z-index: 1000;
  width: 100%;
}

它固定在顶部,但过渡不起作用,我希望 header 用某种 animation 固定在顶部。

如何使用为 div 固定的 position 制作动画?

可以加懒动animation。 不使用position: fixed; 使用 position: absolute 并在 window 的每个滚动端捕获滚动增量并将其设置在 div 上。 伪代码如下:

  • Append 滚动事件
  • 在每个滚动端捕获 Y 滚动 position。
  • 现在在具有position: absolute;

如果这听起来让您感到困惑,那么请告诉我,然后我也可以分享代码。

希望这会有所帮助:)

我解决了将类应用于 div 的问题:

 <div
          className={
            show ? `${classes.navbar} ${classes.navbarSticky}` : classes.navbar
          }
          style={{
            background: bgColor,
            boxShadow: "0 0 10px #ccc",
          }}
        >
          <div className="d-flex justify-content-between p-4">
            <div>{left}</div>
            <div>{right}</div>
          </div>
          {bottom}
        </div>

styles 是:


.navbar {
  position: absolute;
  z-index: 1;
  width: 100%;
  background: red;
}

.navbarSticky {
  background: #333;
  position: fixed;
  top: 0;
  left: 0;
  animation: moveDown 0.5s ease-in-out;
}

@keyframes moveDown {
  from {
    transform: translateY(-5rem);
  }
  to {
    transform: translateY(0rem);
  }
}

@keyframes rotate {
  0% {
    transform: rotateY(360deg);
  }
  100% {
    transform: rotateY(0rem);
  }
}

暂无
暂无

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

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