在某些浏览器中,CSS动画意外地从头开始



在IE11和Webkit浏览器中,如果在包含CSS动画中间元素的div上设置display: none,然后将容器div设置回display: block,则动画将从头开始。

Firefox并没有这样做:它的行为就像动画一直在后台运行一样(这对我来说似乎更直观)。

哪种行为是正确的?

我已经将其提炼为一个基本的测试用例,您可以在这个jsfiddle中看到。在Firefox中尝试,然后在Chrome/Safari/IE11中尝试,并注意行为上的差异。

问题1:哪个浏览器符合此处的规范?还是规格太模糊,说不出来?

问题2:如果一种或另一种行为是兼容的,是否有一种修复/解决方法/破解方法会迫使不兼容的浏览器也正确运行?

我已经读到在上使用visibility: hidden而不是display: none可以防止此问题这不是一个选项

我知道我可以使用jQuery.animate()或其他基于JavaScript的动画技术作为解决方法那不是我要问的

JSFiddle的代码如下所示。

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title> - jsFiddle demo</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
    <style type="text/css">
        #bar {
            width: 100%;
            height: 24px;
            background-color: #fc0;
        }
        #bar.shrinking {
            -moz-animation: shrink 10s linear;
            -moz-animation-fill-mode: forwards;
            -o-animation: shrink 10s linear;
            -o-animation-fill-mode: forwards;
            -webkit-animation: shrink 10s linear;
            -webkit-animation-fill-mode: forwards;
            animation: shrink 10s linear;
            animation-fill-mode: forwards;
        }
        @-moz-keyframes shrink {
            from { width: 100%; } to { width: 0%; }
        }
        @-o-keyframes shrink {
            from { width: 100%; } to { width: 0%; }
        }
        @-webkit-keyframes shrink {
            from { width: 100%; } to { width: 0%; }
        }
        @keyframes shrink {
            from { width: 100%; } to { width: 0%; }
        }
    </style>
    <script>
        $(window).load(function(){
            $("#start-animation").click( function() {
                $("#bar").addClass("shrinking");
            } );
            $("#hide-container").click( function() {
                $("#container").css( "display", "none" );
            } );
            $("#show-container").click( function() {
                $("#container").css( "display", "block" );
            } );
        });
    </script>
</head>
<body>
    <ol>
        <li>
            <button id="start-animation">Start animating the yellow bar</button>
        </li>
        <li>
            While the animation is still running, <button id="hide-container">set display: none on the containing div</button>
        </li>
        <li>
            <button id="show-container">Set the container back to display: block</button>
        </li>
        <li>
            In Webkit and IE11, the animation starts over from the beginning. In Firefox, it behaves as if the animation had been running in the background all along.
        </li>
    </ol>
    <div id="container">
        <div id="bar"></div>
    </div>
</body>
</html>

我不知道关于规格的答案,但就另一种解决方法而言:

你能用不透明代替吗?使用opacity: 0隐藏容器,而不是显示和隐藏来切换显示?

设置时使用动画:http://jsfiddle.net/t5bhmnoy/7/

使用转换-这只是我尝试过的一种方法:http://jsfiddle.net/t5bhmnoy/6/

最新更新