javascript - 从左到右动画 div 宽度
问题描述
我是动画新手,但我想为骨架加载器制作动画。我希望它以 0% 的宽度从左侧开始,然后以 100% 的宽度向右移动,然后让加载程序变为零但反向,以便它以 0% 的宽度在右侧结束。我的问题是我无法让动画从左到右消失。我正在使用带有样式的组件的反应。这是我的代码:
const reveal = keyframes`
0% {
width: 0%;
}
50% {
width: 100%;
}
100% {
width: -100%;
}
`;
const StyledSkeleton = styled.div`
height: 40px;
font-size: 64px;
line-height: 70px;
overflow: hidden;
background-color: ${colors.LOADER_BACKGROUND};
background-size: 100%;
animation-name: ${reveal};
animation-duration: 2s;
animation-timing-function: ease-in;
animation-delay: 0s;
animation-iteration-count: infinite;
animation-direction: normal;
`;
解决方案
您可以使用绝对位置为加载程序的大小设置动画,而不是使用宽度。
.container {
width: 100%;
height: 40px;
position: relative;
}
.loader {
position: absolute;
top: 0;
bottom: 0;
background-color: red;
animation-name: animate;
animation-duration: 2s;
animation-timing-function: ease-in;
animation-iteration-count: infinite;
}
@keyframes animate {
0% {
left: 0;
right: 100%;
}
50% {
left: 0;
right: 0;
}
100% {
left: 100%;
right: 0;
}
}
<div class='container'>
<div class='loader'></div>
</div>