CSS 对对象进行动画处理并保留其新位置

Thu*_*nch 5 css web

<html>
    <head>
        <title>Animation</title>

        <style type="text/css">
            .container
                {
                    background-color: blue;
                    height: 200px;
                    width: 200px;
                    position: relative;
                    -webkit-animation-name:animate;
                    -webkit-animation-duration:1s;  
                }

                @-webkit-keyframes animate  
                {
                    0%
                    {
                    -webkit-transform: translate(0, 0);
                    }

                    100% 
                    {
                    -webkit-transform: translate(100px, 100px);
                    }
                }
        </style>
    </head>

    <body>

    <div class="container">
    </div>

    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

上面的代码对一个对象进行了动画处理,但动画结束后它返回到原始位置。如何将其保留在新位置?这意味着正方形不能返回到 (0,0)

Ash*_*ngh 3

您可以使用该animation-fill-mode财产。

Animation-fill-mode 属性指定动画未播放时(动画完成时或有延迟时)元素的样式。

默认情况下,CSS 动画在第一个关键帧“播放”之前不会影响元素,然后在最后一个关键帧完成后停止。Animation-fill-mode 属性可以覆盖此行为。

- CSS3动画填充模式属性

-webkit-animation-fill-mode: forwards动画完成后,使运动永久化。

.container {
  background-color: blue;
  height: 200px;
  width: 200px;
  position: relative;
  -webkit-animation-name: animate;
  -webkit-animation-duration: 1s;
  -webkit-animation-fill-mode: forwards;
}
@-webkit-keyframes animate {
  0% {
    -webkit-transform: translate(0, 0);
  }
  100% {
    -webkit-transform: translate(100px, 100px);
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
</div>
Run Code Online (Sandbox Code Playgroud)