[英]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 上。 偽代碼如下:
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.