使用 JavaScript 触发和循环 CSS3 动画

Triggering and looping a CSS3 animation using JavaScript

我正在尝试在 input 元素上实现加载动画。我希望在单击页面上的搜索按钮时触发动画,并在搜索返回时停止(在回调中)。

因为我正在使用 AngularJS,目前它被设置为一个 $http.get 调用和关联的 .success 回调,所以我已经有了添加触发和停止。

看看我的 CodePen example 你应该能看出我在做什么。动画应该 运行 像这样:

在我的示例中,我使用了 :hover 来触发动画,但最终应该从 JavaScript.

触发

如何在 JavaScript 中开始和结束动画循环,以及如何让它无限循环直到停止?

[信用]

http://bradsknutson.com/blog/css-sliding-underline

您为什么不想只构建带有动画的关键帧?只需将无限添加到动画迭代计数中即可...

@keyframes slideAnimation {
  0%:{
    width: 0;
    background: transparent;
    }
  100%:{
    width: 100%;
    background: #4ad;}
}
input.animate {
  animation: slideAnimation 800ms ease infinite normal 0ms running;
}

然后只需切换 类 输入即可。

你可以制作一个动画然后切换 class:

HTML

<div class="sliding-u-l-r-l" id="inputElement">
  <input type="text" spellcheck="false" placeholder="Hover over me to demo">
</div>

<input type="button" id="start" value="Start" />
<input type="button" id="stop" value="Stop" />

CSS

.sliding-u-l-r-l {
    display: inline-block;
    position: relative;
    padding-bottom: 2px;
}
.sliding-u-l-r-l.animate:before {
    content: '';
    display: block;
    position: absolute;
    height: 2px;
    width: 0;
    bottom: 0;
    background: #4ad;
    animation: animation 1.5s infinite;
}

@keyframes animation {
  0% {
    left: 0;
    width: 0;
  }  

  50% {
    width: 100%;
    left: 0%;
  }

  100% {
    left: 100%;
    width: 0%;
  }
}

JS

$("#start").on("click", function() {
  $("#inputElement").addClass("animate");
});

$("#stop").on("click", function() {
  $("#inputElement").removeClass("animate");
});

如果你不会,你也可以交替动画(很酷的效果)只需更改:

animation: animation 1.5s infinite;

animation: animation 1.5s infinite alternate;

码笔结果 http://codepen.io/anon/pen/qOQBox