如何暂停 CSS 过渡? [英] How do I pause CSS transition?
问题描述
我需要在过渡期间随时暂停 CSS 过渡.我知道有一个计算过渡属性的当前值并直接应用它的解决方案,但是这给了我在 Safari 和 IE11 中跳跃"的结果.
I need to pause a CSS transition at any time during the transition. I know there is a solution with calculating the current value of the transitioning property and applying it directly, however this gave me "jumping" results in Safari and IE11.
我的想法是将 transition-duration
值增加到更大的值,这在我的理论中应该几乎暂停了过渡,但事实并非如此:
What I though of is to increase the transition-duration
value to something big, that is in my theory should have almost paused the transition, but it seems it's not the case:
https://jsfiddle.net/j8p0msff/
$('#pause').on('click', function() {
$('.ball').css('transition-duration: 5000s');
});
还有其他想法吗?谢谢!
Any other ideas? Thanks!
推荐答案
Transitions
一个解决方案是删除 transition
类并在停止时保存样式的当前状态(在示例中为 margin-left
).开始时只需再次添加 transition
类.
A solution would be to remove the transition
class and save the current state of styles (margin-left
in the example) when stopping. And when starting just add the transition
class again.
var boxOne = document.getElementsByClassName('box')[0];
var running = false;
var toggleTransition = function() {
if(!running)
{
boxOne.classList.add('horizTranslate');
} else {
var computedStyle = window.getComputedStyle(boxOne),
marginLeft = computedStyle.getPropertyValue('margin-left');
boxOne.style.marginLeft = marginLeft;
boxOne.classList.remove('horizTranslate');
}
running = !running;
}
.box {
margin: 30px;
height: 50px;
width: 50px;
background-color: blue;
}
.box.horizTranslate {
-webkit-transition: 3s;
-moz-transition: 3s;
-ms-transition: 3s;
-o-transition: 3s;
transition: 3s;
margin-left: 50% !important;
}
<div class='box'></div>
<button class='toggleButton' onclick='toggleTransition()'>Toggle</button>
动画
您可以使用:animation-play-state
例如Javascript: document.getElementById('myId').style.animationPlayState = 'paused'
With e.g. Javascript: document.getElementById('myId').style.animationPlayState = 'paused'
var toggleAnimation = function(){
state = document.getElementById('myId').style.animationPlayState == 'paused' ? 'running' : 'paused';
document.getElementById('myId').style.animationPlayState = state;
}
div#myId {
width: 100px;
height: 100px;
background: red;
position: relative;
-webkit-animation: mymove 5s infinite; /* Safari 4.0 - 8.0 */
-webkit-animation-play-state: running; /* Safari 4.0 - 8.0 */
animation: mymove 5s infinite;
animation-play-state: running;
}
/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
from {left: 0px;}
to {left: 200px;}
}
@keyframes mymove {
from {left: 0px;}
to {left: 200px;}
}
<div id='myId'></div>
<button onclick="toggleAnimation()">Toggle Animation</button>
这篇关于如何暂停 CSS 过渡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!