设置CSS“动画”进度百分比

时间:2018-06-19 22:01:35

标签: javascript

以下是单击“ HERE”时可更改div高度的代码段。

我希望单击以更改动画进度的百分比(例如,更改为50%)。如何实现?

function f() {
  document.getElementById('id1').style.height = "10px";
}
@keyframes k {
  0% {
    background-color: red;
  }
  100% {
    background-color: blue;
  }
}

.a {
  height: 100px;
  width: 100px;
  animation: k 10s infinite;
}
<div id="id1" class="a"></div>
<div onclick="f()">HERE</div>

1 个答案:

答案 0 :(得分:1)

您可以使用WAAPI(如果需要,可以使用其polyfill):

const hop = (t) => a.currentTime = options.duration * t,

  keyframes = [
    {transform: 'translateX(-100px)', background: 'red'},
    {transform: 'translateX(100vw)', background: 'blue'}
  ],

  options = {
    duration: 4000,
    iterations: Infinity
  },

  a = document.getElementById('id1').animate(keyframes, options)
#id1 {height: 100px; width: 100px;}
<!-- polyfill -->
<script src="https://rawgit.com/web-animations/web-animations-js/master/web-animations.min.js"></script>

<div id="id1"></div>

<!-- 0.5 is for 50% here -->
<button onclick="hop(0.5)">HERE</button>