隐藏元素时CSS动画暂停 [英] CSS Animation pausing when element is hidden
问题描述
我正在努力为我正在处理的项目上的按钮添加点击/触摸动画,并且我遇到了一个令人沮丧的问题,关于动画显示和隐藏元素的按钮。
I'm working on adding click/touch animations to buttons on a project I'm working on, and I've come across a frustrating problem concerning animating buttons which show and hide elements.
该项目是一个单页移动网络应用程序,上面有一些按钮。我正在使用jQuery在按下按钮时在按钮上设置css关键帧动画。该按钮隐藏当前页面,并显示一个新页面。问题是,当我单击按钮时,页面会在动画完成之前更改,并且在隐藏容器时动画会暂停。重新显示容器时,动画将从隐藏的位置继续,然后触发webkitAnimationEnd事件。
The project is a single page mobile web app with a handful of buttons on it. I'm using jQuery to set a css keyframe animation on a button when it's pressed. The button hides the current page, and shows a new one. The problem is, when I click the button, the page changes before the animation is complete, and the animation is paused whilst the container is hidden. When the container is re-shown, the animation continues from where it was hidden, then the webkitAnimationEnd event triggers.
显示和隐藏容器:
display: none;
我无法将其更改为:
visibility: hidden;
因为容器仍占用空间。有什么简单的方法可以在元素变得不可见时强制移除动画,或者在隐藏容器时强制动画继续吗?
because the container will still take up space. Are there any simple ways I can force the animation to be removed when the element becomes invisible, or force the animation to continue when the container is hidden?
编辑:澄清,这是我在javscript中应用的关键帧动画:
For clarification, this is the keyframe animation I'm applying in the javscript:
@-webkit-keyframes shrink
{
0%
{
-webkit-transform: matrix(1, 0, 0, 1, 0, 0);
}
50%
{
-webkit-transform: matrix(0.95, 0, 0, 0.95, 0, 0);
}
100%
{
-webkit-transform: matrix(1, 0, 0, 1, 0, 0);
}
}
这是我必须申请的javascript元素的动画:
And this is the javascript I've got to apply the animation to the element:
$('body').on(_context.settings.platformInfo.device.touch ? 'touchstart' : 'mousedown', '.shrink', function ()
{
var $item = $(this);
$item.one('webkitAnimationEnd', function ()
{
$item.css({ '-webkit-animation': 'none' });
}).css({ '-webkit-animation': 'shrink 250ms forwards' });
});
推荐答案
我找到了一个适用于此的解决方案特别的问题,虽然我并不是非常喜欢它。将setTimeout添加到混合中意味着即使容器被隐藏,动画也会在250ms后移除(在这种情况下)。
I've found a solution which will work for this particular problem, although I'm not massively fond of it. Adding a setTimeout into the mix means that even when the container is hidden, the animation will be removed after 250ms (in this case).
$('body').on(_context.settings.platformInfo.device.touch ? 'touchstart' : 'mousedown', '.shrink', function ()
{
var $item = $(this);
setTimeout(function ()
{
$item.css({ '-webkit-animation': 'none' });
}, 250);
$item.css({ '-webkit-animation': 'shrink 250ms forwards' });
});
这个问题的主要问题是浏览器在执行动画时特别慢,并且超时触发太快切断了动画。
The main problem with this is if the browser is particularly slow at executing the animation, and the timeout fires too soon cutting the animation off.
这篇关于隐藏元素时CSS动画暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!