CSS 动画/精灵表不会停留在最后一个图像上



我有下面的代码

div.sprite {
width: 200px;
height: 194px;
background-image: url("https://www.giftofspeed.com/sprite-generator/sprites/8a7a791467c5d7a9eb8050cdd3dee4fa.png");
animation: play 1s steps(5) 1;
animation-fill-mode: forwards;
}
@keyframes play {
from {
background-position-x: -0px;
}
to {
background-position-x: -974px;
}
}
<div class="sprite">
</div>

问题是我无法让它在最后一帧停止(5((动画似乎也有点偏离(

它一直回到第一个,我在谷歌上搜索了一下,发现很多其他人也有同样的问题,但将步骤从5改为4,或者设置

animation-fill-mode: forwards; 

这似乎是建议的修复对我不起作用。

您应该更正背景位置的最后一个值。您的图像的宽度为974px,因此使用-974px相当于0px,因为存在重复,因此它将从第一个开始。您需要减少它,然后使用steps(4)。您也可以更正div的width以获得更准确的结果:

div.sprite {
width: 194.8px; /* (974/5) */
height: 194px;
background-image: url("https://www.giftofspeed.com/sprite-generator/sprites/8a7a791467c5d7a9eb8050cdd3dee4fa.png");
animation: play 1s steps(4) forwards;
}
@keyframes play {
from {
background-position-x: -0px;
}
to {
background-position-x: -779.2px; /*974 - (974/5)*/
}
}
img {
border:1px solid;
background:repeating-linear-gradient(to right,transparent 0px,transparent calc(100%/5 - 2px),#000 calc(100%/5 - 2px),#000 calc(100%/5));
}
<img src="https://www.giftofspeed.com/sprite-generator/sprites/8a7a791467c5d7a9eb8050cdd3dee4fa.png" height=50>
<div class="sprite"></div>

相关内容

最新更新