这是一个使用 CSS 关键帧的简单脉动动画。
问题是如果我想丢弃或删除动画中间的动画,动画会突然停止(突然跳转到其初始状态,如您在代码片段中所见)。
我希望动画顺利回到初始状态,即使你在动画中间停止它也是如此。
接受 JQuery 和 TweenMax。
有什么办法吗?
let test = document.getElementById("test");
setTimeout(function(){
test.classList.add("addAniamte");
}, 2000)
setTimeout(function(){
test.classList.remove("addAniamte");
test.classList.add("removeAniamte");
console.log('stoping aniamtion!');
}, 4500)
@-webkit-keyframes pulse {
0% {
-webkit-transform: scale(1, 1);
}
50% {
-webkit-transform: scale(3, 3);
}
100% {
-webkit-transform: scale(1, 1);
};
}
#test {
background: red;
width: 20px;
height: 20px;
margin: 60px;
}
.addAniamte{
-webkit-animation: pulse 1s linear infinite;
animation: pulse 1s linear infinite;
}
.removeAniamte{
-webkit-animation: none;
animation:none;
}
<div id="test"></div>
最佳答案
使用 GSAP 很容易做到这一点!以下是如何在 GSAP 3 中执行此类操作。
var tween = gsap.from("#test", {duration: 1, scale: 0.33, repeat: -1, yoyo: true, paused: true});
function startAnimation() {
tween.play();
}
function stopAnimation() {
tween.pause();
gsap.to(tween, {duration: 0.5, progress: 0});
}
#test {
background: red;
width: 60px;
height: 60px;
margin: 60px;
}
<div id="test"></div>
<button onclick="startAnimation()">Start</button>
<button onclick="stopAnimation()">Stop</button>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.0.4/dist/gsap.min.js"></script>
如果没有 GSAP(或者至少是一种仅使用 JS 的方法),它就会像其他答案所示那样非常困惑且容易出错。事实上,我有 my own question这导致 a CSS-Tricks article关于这个问题。
关于javascript - 如何正确地在中间停止动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59337873/