如何使CSS动画按需向前或向后播放

时间:2018-08-29 20:23:20

标签: javascript html css css-animations

我有一个CSS动画,根据某些情况,我希望能够基于某些JS在任何时候向前或向后切换。这是一个基本示例:

html

<div id="box"></div>
<button onclick="toggle()">toggle</button>

js

window.isSmall = true;
window.toggle = function() {
    if (isSmall) {
    var el = document.getElementById("box");
    el.classList.add("bigger");
  } else {
    // ????
  }
  isSmall = !isSmall;
}

css

@keyframes bigger {
    from { width:100px; height:100px; }
    to { width:200px; height:200px; }
}

#box {
    width:100px;
    height:100px;
    background-color: red;
}

.bigger {
    animation-name: bigger;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}

提琴: http://jsfiddle.net/gbh408up/

我认为这很简单,但是令人惊讶的是我无法找到一种方法来实现这一目标。注意,我专门在寻找动画而不是过渡的解决方案。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您可以使用2个类来制作所需的动画。

run_as_user
window.isSmall = true;
window.toggle = () => {
  const box = document.getElementById("box");
  if (isSmall) {
    box.classList.remove("smaller");
    box.classList.add("bigger");
  } else {
    box.classList.remove("bigger");
    box.classList.add("smaller");
  }
  isSmall = !isSmall;
  console.log(isSmall)
}
@keyframes bigger {
  from {
    width: 100px;
    height: 100px;
  }
  to {
    width: 200px;
    height: 200px;
  }
}

@keyframes smaller {
  from {
    width: 200px;
    height: 200px;
  }
  to {
    width: 100px;
    height: 100px;
  }
}

#box {
  width: 100px;
  height: 100px;
  background-color: red;
}

.bigger {
  animation-name: bigger;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

.smaller {
  animation-name: smaller;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

答案 1 :(得分:1)

我刚刚弄清楚了这一点。所以这是我的解决方案:

<div id="box"></div>

<button onclick="toggle()">toggle</button>

window.isSmall = true;
window.toggle = function() {
    var el = document.getElementById("box");
    if (el.className == "a") {
    el.className = "b";
    } else {
    el.className = "a";
  }
  isSmall = !isSmall;
  console.log('toggle');
 }


@keyframes a {
    from { width:100px; height:100px; }
    to { width:200px; height:200px; }
}
@keyframes b {
    from { width:200px; height:200px; }
    to { width:100px; height:100px; }
}

#box {
    width:100px;
    height:100px;
    background-color: red;
}

.a {
    animation-name: a;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}
.b {
  animation-name: b;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}

我将“较大”更改为“ a”,将“较小”更改为仅“ b”。但这有效。好的-我现在把它放在小提琴中。

https://jsfiddle.net/markem/2b6n3gmc/1/

此外,在StackOverflow上,此问题对此有所回答:

Javascript simple add class remove class