javascript - 使用 javascript 操作 CSS 动画

标签 javascript

这是一个简单的问题,但我对编程还很陌生,我不太确定如何做到这一点。

我有一个在按下按钮时移动的 div

var checkbox = document.getElementById('checkbox');
var box = document.getElementById('box');

box.addEventListener('click', function() {
  checkbox.checked = true;
});
#box {
  position: absolute;
  transform: translate3d(0, 0, 0);
  height: 20%;
  width: 20%;
  background-color: red;
 }

@keyframes moveRight {
  0% {
    transform: translate3d(0, 0, 0);
  }
  60% {
    transform: translate3d(120%, 0, 0);
  }
  100% {
    transform: translate3d(100%, 0, 0);
  }
 }

#checkbox:checked ~ #box {
  animation-name: moveRight;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}
<!DOCTYPE html>
<html>
  <body>
    <input type="checkbox" id="checkbox" />
    <div id="box">
    </div>
  </body>
 </html>

这是一个简单的动画,因此对于这种情况来说,这样做并不是真正的问题。问题是当我想通过复选框添加另一个动画时,它会看到两个复选框都被“选中”并且它会运行两个动画。使用 javascript 并且没有复选框,我该如何执行以下操作:

-添加CSS动画 - 当我想使用其他动画时将其删除

谢谢!

最佳答案

例如,这可以通过添加/删除框元素的 css 类来完成。 (如果我正确理解你的问题)

var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var box1 = document.getElementById('box1');

button1.addEventListener('click', function() {
    box1.className = "";
    box1.className += " moving-box-right";
});
button2.addEventListener('click', function() {
    box1.className = "";
    box1.className += " moving-box-left";
});


#box1 {
  position: absolute;
  transform: translate3d(0, 0, 0);
  height: 20%;
  width: 20%;
  background-color: red;
 }

@keyframes moveRight {
  0% {
    transform: translate3d(0, 0, 0);
  }
  60% {
    transform: translate3d(120%, 0, 0);
  }
  100% {
    transform: translate3d(100%, 0, 0);
  }
 }
 @keyframes moveLeft {
  0% {
    transform: translate3d(100%, 0, 0);
  }
  100% {
    transform: translate3d(0%, 0, 0);
  }
 }

.moving-box-right {
  animation-name: moveRight;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}
.moving-box-left {
  animation-name: moveLeft;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}


<!DOCTYPE html>
<html>
  <body>
    <button id="button1">Move box right</button>
     <button id="button2">Move box left</button>
    <div id="box1"></div>
  </body>
 </html>

https://jsfiddle.net/kdnzqx52/2/

关于javascript - 使用 javascript 操作 CSS 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35352430/

相关文章:

javascript - 在 facebook 登录中获取 CSI/tbsd_ & CSI/_tbnd 数据

递归函数中的 JavaScript promise

javascript - 使用 this.inherited 在 dojo 中调用祖 parent 方法

javascript - 带有超时功能的 Google 标记掉落动画

javascript - 三.js改 Material

javascript - 使用范围变量作为函数中的参数并使用其引用而不是值

javascript - 调试器;在 Chrome 控制台中

javascript - 方便的自动完成项目排序

php - 将 Javascript 正则表达式转换为 PHP (PCRE) 表达式

javascript - 怎样写三 Angular 形的面积和周长