问题
I have a CSS keyframe animation that, in itself, is pretty ordinary. However, I want to be able to force the animation to be at a particular frame. Something like anim.setProgress(0.13)
, which would set the animation to be 13% along. How can I do that?
Note that I don't just want to start the animation at an arbitrary point. I want to be able to interrupt it and say "go back to 32%" or something, regardless of how far along the animation is.
回答1:
Give the animation a negative animation-delay
value. For an animation that runs for 10 seconds, the frame at 13% would be targeted with -1.3s
.
Documentation
If the value for ‘animation-delay’ is a negative time offset then the animation will execute the moment it is applied, but will appear to have begun execution at the specified offset. That is, the animation will appear to begin part-way through its play cycle. In the case where an animation has implied starting values and a negative ‘animation-delay’, the starting values are taken from the moment the animation is applied.
Example
div.loading {
animation: loading 10s linear 1;
animation-play-state: paused;
animation-delay: -1.3s;
/*start at 13%*/
}
div.ten-seconds {
animation-delay: -1s;
/*start at 10%*/
}
div.zero-seconds {
animation-delay: 0s;
/*start at 0%*/
}
/*Note how the keyframes start at 0 width*/
@keyframes loading {
0% {
width: 0;
}
100% {
width: 100%;
}
}
/*Just for this example below*/
input {
display: none
}
label {
display: block;
background: gray;
width: 120px;
height: 50px;
line-height: 50px;
text-align: center;
font-size: 20px;
margin: 20px 0 20px 0;
color: #FFF;
cursor: pointer;
}
input:checked ~ .loading {
animation-play-state: running;
}
div {
height: 100px;
background: pink;
}
div.ruler {
width: 13%;
height: 20px;
line-height: 20px;
text-align: center;
color: #FFF;
background: gray;
border-bottom: solid 2px #000;
}
div.ruler.bottom {
width: 10%;
}
<input type="checkbox" id="start" />
<label for="start">Start / Pause</label>
<div class="ruler">Go 13%</div>
<div class="loading"></div>
<div class="ruler bottom">Go 10%</div>
<div class="loading ten-seconds"></div>
<h2>No delay below</h2>
<div class="loading zero-seconds"></div>
来源:https://stackoverflow.com/questions/39322274/how-do-i-set-the-current-frame-or-similar-of-a-css-animation