【问题标题】:Css animation - stop and revert animationCss 动画 - 停止和恢复动画
【发布时间】:2017-09-29 07:37:29
【问题描述】:

我希望我的自定义元素在单击按钮时向右移动 200 像素。所以元素在点击时开始移动。在动画中我希望能够再次单击按钮停止并让元素动画返回初始状态(从当前状态反转动画)。

我通过 css 转换完成了这个:

var state = false;
var button = document.getElementById("but");

button.onclick = clickA;

function clickA(){
  
  state = !state;
  
  var el = document.getElementById("el");
  if (state) el.setAttribute("class", "animatedElement open");
  else el.setAttribute("class", "animatedElement");
}
.animatedElement {
  padding-left: 0px;
  transition: padding-left 5s;
}

.open {
  padding-left: 200px;
}
<button id="but">Click</button>
<div id="el">element</div>

所以点击时我只需切换组件上的.open 类。

我想知道这是否可能与 css 动画有关?我试过这个:

var state = false;
var button = document.getElementById("but");

button.onclick = clickA;

function clickA(){
  
  state = !state;
  
  var el = document.getElementById("el");
  if (state) el.setAttribute("class", "animatedComponent-open");
  else el.setAttribute("class", "animatedComponent-close");
}
@keyframes animationOpen {
  0% {padding-left: 0px;}
  100% {padding-left: 200px;}
}
.animatedComponent-open {
  animation: animationOpen 3s normal forwards;
}
    
@keyframes animationClose {
  0% {padding-left: 0px;}
  100% {padding-left: 200px;}
}
.animatedComponent-close {
  animation: animationClose 3s reverse forwards;
}
<button id="but">Click</button>
<div id="el">element</div>

但这不会在动画中间点击时恢复打开的动画,而是跳转到最终状态,然后从头开始播放关闭动画。

【问题讨论】:

    标签: javascript css css-animations frontend keyframe


    【解决方案1】:

    由于关键帧有起点和终点,所以无论元素的当前位置在哪里,它们都会从这些位置开始。由于您使用 js 进行切换,因此过渡是要走的路。动画只是让它变得更加复杂而没有任何好处。

    【讨论】:

      【解决方案2】:

      访问https://css-tricks.com/controlling-css-animations-transitions-javascript/

      我相信这篇文章会给你确切的答案。有许多变通方法可以在暂停的动画播放状态下获取当前关键帧值。 然后使用这些值,您可以使用 animate api 构建反向动画。 如果您可以传递反向动画,则将暂停关键帧值作为起始位置值。然后,您可以将动画结束关键帧设置为 paddingLeft:0px - 就是它的开始方式。

      这将解决不需要的跳转到动画结尾的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-01
        • 2018-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-17
        • 2015-07-06
        相关资源
        最近更新 更多