简体   繁体   English

CSS-类添加/删除上的过渡动画

[英]CSS - transition animation on class add/remove

I'm trying to set a transition to a transform that is applied as part of a animation. 我正在尝试设置过渡到作为动画一部分应用的变换。 In this codepen example and inline here, I'm adding a class to start/stop the animation keyframes. 在此codepen示例和此处的内联代码中,我添加了一个类来启动/停止动画关键帧。 When the button is clicked to stop the rotation, it snaps back to the start frame. 单击该按钮停止旋转时,它将捕捉回到起始帧。

Is it possible to have it either complete the rotation or smoothly roll back to it's start state? 它是否可以完成旋转或平稳回滚到其初始状态?

 var toggle2d = document.getElementById('toggle-2d'); var plain = document.querySelector('.plain'); toggle2d.onclick = () => { plain.classList.toggle('animate-2d'); } 
 .plain { top: 50%; left: 50%; display: flex; align-items: center; justify-content: center; position: absolute; } .orbit { width: 200px; height: 200px; border: 1px solid black; border-radius: 50%; display: flex; align-items: center; justify-content: flex-end; position: absolute; transform-style: preserve-3d; transition: all 1s linear; } .body { width: 30px; height: 30px; background-color: brown; border-radius: 50%; display: flex; align-items: center; justify-content: center; transform-style: preserve-3d; } .animate-2d .orbit { transition: all 1s linear; animation: orbit-cw infinite linear; animation-duration: 5s; animation-fill-mode: both; } @keyframes orbit-cw { 100% { transform: rotateZ(360deg); } } 
 <button type="button" id="toggle-2d">toggle 2d</button> <div class="plain"> <div class="orbit"> <div class="body"> </div> </div> </div> 

You can use the animationiteration event to achieve this. 您可以使用animationiteration事件来实现此目的。

var stopRequested = false;

toggle2d.onclick = () => {
    stopRequested = !stopRequested;
    if(!stopRequested) {
        plain.classList.add('animate-2d');
    }
}

plain.addEventListener("animationiteration", function(){
    if(stopRequested){
        plain.classList.remove('animate-2d');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM