在Safari中的CSS动画错误
我有一个延迟的CSS动画,我在延迟期间暂停它。 它在Firefox和Chrome上按预期工作,“Hello”不会移动。 但是在Safari上,动画跳转到最后一帧。 为什么以及如何修复?在Safari中的CSS动画错误
function test() {
var timeout = 1000;
setTimeout(function() {
document.getElementById('animation').style.animationPlayState = 'paused';
}, timeout);
}
document.addEventListener("DOMContentLoaded", test);
#animation {
animation: test 2s linear 2s;
}
@keyframes test {
to {
transform: translateY(100px);
}
}
<div id="animation">
Hello (this text should not move)
</div>
如果我删除了2秒延时,设置持续时间4秒,并添加关键帧与变换:没有,我可以让这个简单的例子工作。不过,我真实的情况下有多个动画,与延迟同步。
这不是问题的答案。但是,如果您删除动画延迟,暂停并重新启动动画就像它应该那样工作。看起来动画延迟是导致问题的原因。也许而不是依靠CSS来处理延迟,用JavaScript编程控制动画延迟。
见下文暂停和运行动画
function test() {
var timeout = 1000;
setTimeout(function() {
document.getElementById('animation').style.animationPlayState ='paused';
document.getElementById('animation').style.webkitAnimationPlayState ='paused';
}, timeout);
setTimeout(function() {
document.getElementById('animation').style.animationPlayState='running';
document.getElementById('animation').style.webkitAnimationPlayState ='running';
}, timeout * 2);
}
document.addEventListener("DOMContentLoaded", test);
#animation {
-webkit-animation: test 2s linear;
animation: test 2s linear;
}
@-webkit-keyframes test {
to {
-webkit-transform: translateY(100px);
transform: translateY(100px);
}
}
@keyframes test {
to {
-webkit-transform: translateY(100px);
transform: translateY(100px);
}
}
<div id="animation">
Hello (this text should not move)
</div>
Safari的行为是只有当超时设置为比动画延迟小的值马车。所以,一个的解决方法是通过animation-play-state
设置初始状态到paused
,然后通过JS控制它,如下图所示:
function test() {
let el = document.getElementById("animation");
let timeout = 1000;
// Get the delay. No luck with el.style.animationDelay
let delay =
window
.getComputedStyle(el)
.getPropertyValue("animation-delay")
.slice(0, -1) * 1000;
// Only resume and later pause when timeout is greater than animation delay
if (timeout > delay) {
el.style.animationPlayState = "running";
setTimeout(function() {
el.style.animationPlayState = "paused";
}, timeout);
}
}
document.addEventListener("DOMContentLoaded", test);
#animation {
animation: test 2s linear 3s;
animation-play-state: paused; /* Pause it right after you set it */
}
@keyframes test {
to {
transform: translateY(100px);
}
}
<div id="animation">
Hello (this text should not move)
</div>
尝试不同的超时值,以查看它的工作。不能说这是为什么发生。对我来说看起来像一个bug。测试OS X El Capitan 10.11.6/Safari 11.0(11604.1.38.1.7)。
谢谢,我也来过结论是这是一个错误,尤其是因为我发现了其他错误.Safari看起来令人难以置信的错误与动画。我想我必须重新在JavaScript中的一切。 – Patrick
无法重现。在Safari 11.0(macOS)中,它按预期工作。 – Styx
@Styx我刚刚在Safari 11.0中测试过,错误仍然存在。 “你好”跳到底部而不是暂停。 – Patrick
请尝试这个jsfiddle,请:https://jsfiddle.net/iStyx/2uqf1p9y/ – Styx