CSS 多个animation一个接一个依次执行

江河/ 2023年04月02日/ CSS教程/ 浏览 1745

比较复杂的动画,难以使用一个animation描述,能否分解成多个animation,然后依次执行呢?


经过一番搜索,发现浏览器又强大了,css 中依次执行多个 animation 已经不能算是一个复杂的任务了。


只需要计算好各个动画开始的时间,然后设置好 animation-delay 就可以了。比如下面的例子,将第二个 animation 的 animation-delay 与 第一个 animation 的 animation-duration 设置成一样的。


<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>css animation</title>
    <style>
        .pan {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: red;

            animation: first 5s 1 forwards, second 5s 1 5s;
        }

        @keyframes first {
            from {
                top: 0px;
            }

            to {
                top: 100px;
            }
        }

        @keyframes second {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(180deg);
            }
        }
    </style>
</head>

<body>
    <div id="ele" class="pan"></div>
</body>


最后的效果就是,先向下移动100px,然后转动180度。


如果,借助 js 的话,可以实现的方式就更灵活一些。


比如可以监听动画结束事件,参考文章:《css animation 动画开始事件和结束事件》,在事件结束的时候,开始另一个动画。


也可以使用 setTimeout,同上面的例子一样,设置延迟时间和第一个动画的执行时间一样,然后执行第二个动画。


如果使用了 JQuery ,就可以使用 jQuery 的 animate 方法,既支持动画结束回调,又支持链式操作,使用起来非常方便。


<script src="js/jquery.min.js"></script>
<script>
    $(function () {
        $('#ele').animate({top:'100px'}, 5000).animate({left: '100px'}, 5000)
    });
</script>


上面的代码是先向下移动100px,然后向右移动100px。比较遗憾的是 jQuery 的 animate 方法支持的 css 属性有限,有些动画效果无法实现……


发表评论

暂无评论,抢个沙发...

客服 工单