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

标签 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;
}

fiddle : http://jsfiddle.net/gbh408up/

我认为这会非常简单,但令人惊讶的是我无法找到实现此目的的方法。请注意,我专门寻找带有动画而不是过渡的解决方案。有什么想法吗?

最佳答案

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

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;
}
<div id="box"></div>
<button onclick="toggle()">toggle</button>

关于javascript - 如何使CSS动画按需向前或向后播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52085536/

相关文章:

javascript - 将对象添加到数组

javascript - 如何判断图像是否未在 Angular 中加载?

javascript - 如何通过 Handlebars 中的索引访问和迭代数组项?

javascript - css 属性在 class.col 函数中无法正常工作

html - ReactJS如何创建罗马数字格式的列表 "ol"或 "ul"

html - 网站在 Safari 中表现异常

javascript - 使用 Javascript 导航方法时检测到错误的语言

HTML 表格标题无法居中,带有引导模式表格数据

html - flexbox 内的自动换行不起作用

javascript - 我的立方体消失了,我不知道为什么