如何用js使得一个已经结束的css的animation动画重新执行一遍

html-css012

如何用js使得一个已经结束的css的animation动画重新执行一遍,第1张

可以试试移除动画的类再重新给节点添加动画的类

下面这个demo是执行一次动画,2s后再重新执行一遍

(因为是demo,我就没有考虑兼容性问题,没有添加css前缀)

1

<div class="dot anm" id="anm"></div>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

.dot {

position: relative

width: 100px

height: 100px

margin: 100px

border-radius: 50%

background: #000

}

.anm {

animation: move 1s forwards

}

@keyframes move

{

from {

left:0px

}

to {

left:200px

setTimeout(function() {

var dom = document.getElementById('anm')

dom.className = 'dot'

setTimeout(function() {

dom.className = 'dot anm'

}, 10)

}, 2000)

<html>

    <head>

        <style>

            @keyframes longer {

                from {width: 100px}

                to {width: 200px}

            }

            @-moz-keyframes longer {

                from {width: 100px}

                to {width: 200px}

            }

            @-webkit-keyframes longer {

                from {width: 100px}

                to {width: 200px}

            }

            @-o-keyframes longer {

                from {width: 100px}

                to {width: 200px}

            }

            #animator {

                width: 100px

                height: 100px

                background: red

            }

            .animation {

                animation: longer 0.5s

                -moz-animation: longer 0.5s

                -webkit-animation: longer 0.5s

                -o-animation: longer 0.5s

            }

        </style>

    </head>

    <body>

        <div id="animator" class="animation"></div>

        <script>

            var animator = document.getElementById('animator')

            animator.addEventListener('animationend', endHandler)

            function endHandler() {

                animator.removeEventListener('animationend', endHandler)

                animator.className = ''

                setTimeout(function () {

                    animator.className = 'animation'

                }, 0)

            }

        </script>

    </body>

</html>

transform 不会使DOM脱离文档流,当通过 translateX 等属性值移动了元素后,它仍然占据原来的位置。

好处是, transform 制作的动画会直接进入合成阶段,避开重排重绘,可以通过 Performance 录制面板来查看 transform 动画的效率。

MDN animation

深入浅出CSS动画

MDN animate()

监听 CSS animation 动画的事件:

这些监听事件对 animate() 是无效的。

页面顶部经常会见到水平无限轮播的公告。

由于轮播的内容是动态的,可能很多,也可能很少,如果公告内容的宽度没有超过最大宽度限制,那么就不应该轮播,如果超过了,则发起轮播。

假设我们永远只有一条最新的公告

原理:当一次动画执行结束时,影子内容的头部刚好对准轮播内容的初始位置,那么下次动画开始时,轮播内容将重新回到初始位置,由于影子内容与轮播内容相同,那么就给人造成一种无限轮播的错觉。

逻辑实现:父元素设置了 overflow: hidden ,又想要获取父元素、子元素的真实宽度,那么可以通过 scrollWidth 获取。

兼容性:如果不支持 animate() ,那么我们可以动态创建 <style>+ @keyframes ,插入 <head>, 但也要记得移除。