在 gatsby 中,我有一个元素,它有一个初始的 css 动画。
静态网站加载时,它开始播放得很好,但在水合后,它会重复播放。
有什么办法可以预防吗?
这是我的风格(我使用了样式组件):
const Container = styled.main<{fontSize:number}>`
@keyframes fadeIn {
from {
opacity: 0;
background-position-y: -100px;
}
to {
opacity: 1;
background-position-y: 0px;
}
}
text-align: center;
padding-top: 2em;
min-height: 330px;
box-sizing: content-box;
position: relative;
font-size: ${(props) => props.fontSize + "px"};
background: ${(props) => props.theme.backgroundImage};
background-position-x: center;
background-position-y: -100px;
background-repeat: no-repeat;
background-size: 715px;
${media.mobile`
background-size: 100vw;
`}
opacity: 0;
animation: fadeIn 1s;
-webkit-animation-fill-mode: forwards;
`;
谢谢
您可以在 CSS 选择器前加上类
.no-js
的前缀。当服务器渲染页面时,该类默认处于“打开”状态,例如 <body class="no-js">
。
您的选择器将如下所示:
.no-js .my-element {
/* animation */
}
或者对于样式组件,
body.no-js & {
/* animation */
}
然后,在组件中使用 JavaScript 来删除水合后的
.no-js
类。
useEffect(() => {
document.body.classList.remove('no-js');
}, []);