Reb*_*cca 7 css animation reverse css3 css-animations
我在CSS中使用了两个关键帧动画.一个从左向右移动,另一个使用完全相同的值 - 但相反.
@keyframes moveLeft
{
from {transform: translate3d(50px, 0, 0);}
to {transform: translate3d(0px, 0, 0);}
}
@keyframes moveRight
{
from {transform: translate3d(0px, 0, 0);}
to {transform: translate3d(50px, 0, 0);}
}
Run Code Online (Sandbox Code Playgroud)
但是,我想知道是否可以只使用一个关键帧动画.但是一旦我添加animation-direction: reverse,动画只播放一次.它可能会保存以前曾使用过的信息.那么:我能以某种方式重置这些信息吗?或者是否有可能在不同的方向上使用一次动画两次?(不使用JS)
不,仅使用 CSS 无法重新启动动画。您必须使用 JavaScript 从元素中删除动画,然后将其重新应用到元素(延迟后)以使其重新启动。
\n\n下面是W3C 的 CSS3 动画规范的内容(在不同的上下文中,但这一点也适用于这种情况):
\n\n\n\n\n另请注意,更改 \xe2\x80\x98animation-name\xe2\x80\x99 的值并不一定会重新启动动画(例如,如果应用了一系列动画并从列表中删除了一个,则只有该动画才会停止;其他动画将继续)。为了重新启动动画,必须将其删除然后重新应用。
\n
重点是我的
\n\nChris Coiyer 的这篇CSS Tricks 文章也指出了同样的情况,并提供了一些用于重新启动动画的 JS 解决方案。(注意:这篇文章引用了 Oli 的 dabblet,它声称更改持续时间、迭代计数等属性会使其在 Webkit 上重新启动,但它似乎已经过时,因为它们不再在 Chrome 上工作)。
\n\n概括:
\n\n虽然您已经谈到了以下内容,但为了完整起见,我将再次重申:
\n\n:checked(尽管方向不同)时,UA 不会执行任何操作,因为动画已存在于元素上。transform中应用了:checked。动画的存在没有任何区别。解决方案:
\n\n正如您从下面的代码片段中看到的,即使使用 JavaScript,通过单个动画实现这一点也相当复杂。
\n\nvar input = document.getElementsByClassName("my-checkbox")[0];\r\n\r\ninput.addEventListener(\'click\', function() {\r\n if (this.checked) {\r\n this.classList.remove(\'my-checkbox\');\r\n window.setTimeout(function() {\r\n input.classList.add(\'anim\');\r\n input.classList.add(\'checked\');\r\n }, 10);\r\n } else {\r\n this.classList.remove(\'anim\');\r\n window.setTimeout(function() {\r\n input.classList.remove(\'checked\');\r\n input.classList.add(\'my-checkbox\');\r\n }, 10);\r\n }\r\n});Run Code Online (Sandbox Code Playgroud)\r\ninput {\r\n transform: translate3d(50px, 0, 0);\r\n}\r\n.my-checkbox {\r\n animation: moveLeft 1s;\r\n animation-direction: reverse;\r\n}\r\n.checked {\r\n transform: translate3d(0px, 0, 0);\r\n}\r\n.anim{\r\n animation: moveLeft 1s;\r\n}\r\n@keyframes moveLeft {\r\n from {\r\n transform: translate3d(50px, 0, 0);\r\n }\r\n to {\r\n transform: translate3d(0px, 0, 0);\r\n }\r\n}Run Code Online (Sandbox Code Playgroud)\r\n<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>\r\n<input type="checkbox" class="my-checkbox">Run Code Online (Sandbox Code Playgroud)\r\n所以,最好的选择(如果你想坚持使用 CSS 动画)是使用两种不同的动画。
\n\n或者,您也可以看看马塞洛的评论。如果实际的用例正是小提琴中提供的,那么transition就足够了并且animation不是必需的。过渡本质上可以向前和向后方向进行,因此是一个更安全的选择。