用javascript操纵CSS动画

时间:2016-02-11 23:56:55

标签: 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>
&#13;
&#13;
&#13;

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

- 添加一个css动画 - 当我想使用另一个动画时删除它

谢谢!

1 个答案:

答案 0 :(得分:1)

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

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/