过渡完成时开始关键帧动画 (CSS)

时间:2021-07-02 20:12:10

标签: css

我想寻求帮助以实现我的想法:一旦 image1 完成转换,“anim”动画就会开始。

我尝试了什么:

我尝试使用“animation-delay”来实现,但这不是我的选择 - 关键是“animation-delay”在执行之后添加了一个时间单击鼠标,我需要动画在过渡结束后立即开始。如果不清楚,我会更简单地说:当您单击并稍微按住多次image1时,过渡不会重新开始,而是“动画延迟”在最后一次鼠标之后重新开始点击。

.image2{
  top:0px;
  left:300px;
  position: absolute;
}
.image1{
  transition: transform 2s;
}

.image1:active{
  transform: scale(0.6);
}

.image1:active + .image2{
  animation: anim 2s;
}

@keyframes anim {
  0%   {top:0%;}
  100% {top:20%;}
}
<div class="test">
<img class="image1" src="http://www.clker.com/cliparts/2/p/6/C/i/q/run-button-md.png">
<img class="image2" src="https://lh3.googleusercontent.com/gti0MtNnT1rEQOuo9mfPfegw-qRGLI1MS3QqamM243fVcIXWqJHmlwldYpBJAwsd3tkQtIfvBqernahhDjuzSw=s200">
</div>

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您可以监听 transitionend 事件,然后添加启动关键帧动画的类。

CSS

.animationclass {
    animation: anim 2s;
 }

JS

const img1 = document.querySelector('.image1');

img1.addEventListener('transitionend', () => {
     console.log('Transition ended, add keyframe animation')
     img1.classList.add("animationclass")
});

答案 1 :(得分:0)

假设一点JS没问题,你可以感觉到image1的过渡什么时候结束,然后开始image2的动画。但是你还需要感知这个动画的结束,以便你可以重置它,下次它会再次播放(否则 CSS 认为它已经完成并且不会重播)。

const test = document.querySelector('.test');
const image1 = document.querySelector('.image1');
const image2 = document.querySelector('.image2');

image1.addEventListener('transitionend', function () {
  image2.classList.add('active');  
});

image2.addEventListener('animationend', function () {
  image2.classList.remove('active');
});
.image2{
  top:0px;
  left:300px;
  position: absolute;
}
.image1{
  transition: transform 2s;
}

.image1:active{
  transform: scale(0.6);
}

.image2.active{
  animation: anim 2s;
}

@keyframes anim {
  0%   {top:0%;}
  100% {top:20%;}
}
<div class="test">
<img class="image1" src="http://www.clker.com/cliparts/2/p/6/C/i/q/run-button-md.png">
<img class="image2" src="https://lh3.googleusercontent.com/gti0MtNnT1rEQOuo9mfPfegw-qRGLI1MS3QqamM243fVcIXWqJHmlwldYpBJAwsd3tkQtIfvBqernahhDjuzSw=s200">
</div>