【发布时间】:2017-12-23 22:57:32
【问题描述】:
是否可以提前结束 CSS 动画,基于从开始的毫秒数,并且仍然触发 transitionend 事件?
小提琴开始
https://jsfiddle.net/Slava_B/4vLwtyxx/
编辑:过渡持续时间和提前停止前的持续时间是在过渡开始之前在 JS 中计算的。同样在现实生活中,通过使用 JS 应用内联样式来触发转换。不知道有没有帮助。
var animateEl = document.querySelector('.animate'),
resultEl = document.querySelector('.result');
animateEl.addEventListener('transitionstart', function(e){
window.animationStartTime = performance.now();
resultEl.innerHTML = '';
})
animateEl.addEventListener('transitionend', function(e){
resultEl.innerHTML = 'Animation took: '+ Math.round(performance.now()-window.animationStartTime) +'ms';
});
.parent{
height:300px;
box-shadow:0 -100px 0 0 rgb(255,150,150) inset, 0 -200px 0 0 rgb(150,255,150) inset;
}
.animate{
height:100px;
background-color:rgba(0,100,200,0.6);
transition:height 2000ms cubic-bezier(0.645,0.045,0.355,1);
}
.animate:hover{
height:300px;
}
<div class="parent">
<div class="animate">
We want to launch the animation for the duration of 2000ms, but prematurely end it for example after 1000ms. So it doesn't reach red zone.
</div>
</div>
<p class="result"></p>
【问题讨论】:
-
您可以使用动画 CSS 属性,然后在关键帧内以您希望它停止/停止的完成百分比来定义所需的 CSS 样式。但您实际上是在保留一个状态,而不是实际停止动画。
-
@Highdef 感谢您的评论,我已经进行了编辑,该评论应该澄清现实世界的用途。如果直到动画开始之前 % 才知道,您认为关键帧是否仍会在解决方案中发挥作用?还有多个元素同时动画,定义关键帧不会破坏其他元素的过渡吗?如果没有,你能做一个小提琴来展示它的样子吗?
-
好吧,就像你说的,如果在持续时间之前不知道 % 时间,那么关键帧将没有任何用处,因为这需要是动态的,然后唯一的解决方案就是转向到 javascript。
-
jsfiddle.net/nesohv7n(动画在 1ms 处停止,直到悬停才恢复)和jsfiddle.net/xw7wcw54(动画停止并返回初始位置)就 CSS 能力而言。
标签: javascript css dom-events css-animations