我们如何添加按钮来切换css动画

时间:2018-01-22 10:53:33

标签: javascript jquery html css css3

我想添加按钮以切换此fiddle的动画。我添加了以下代码,但我无法切换(启动和停止)动画。

body .a [class^="b"] {
  width: 200px;
  height: 142.8571428571px;
  margin: 0 auto;
  position: relative;
  left: 71.4285714286px;
  -webkit-transform-origin: bottom left;
  transform-origin: bottom left;
  border-radius: 100% 300%;
  background: radial-gradient(bottom left, transparent 41.4285714286px, #ff0c0c 41.4285714286px, #3f0000 -15px, #ff0c0c 71.4285714286px);
  /*  -webkit-box-shadow: 71.4285714286px 71.4285714286px 142.8571428571px darkred;*/
  box-shadow: 71.4285714286px 71.4285714286px 142.8571428571px rgb(164, 69, 14);
  -webkit-animation-duration: 5s;
  animation-duration: 0.5s;
  -webkit-animation-delay: 1s;
  animation-delay: 1s;
  -webkit-animation-timing-function: linear;
  animation-timing-function: linear;
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite;
}

1 个答案:

答案 0 :(得分:0)

演示在这里:https://jsfiddle.net/xianshenglu/bjwhm3bf/3/

首先,我将此代码删除为html,并将其值更改为停止

<input type="button" id="button" value="stop"></input>

第二,我给按钮css:

body #button {
  z-index:1;
  position:absolute;
  left:0;
  top:0;
}

第三,我添加了这个javascript:

  document.getElementById('button').addEventListener('click', function() {
  var animationPlayStateEle = document.querySelectorAll('.a [class^="b"]');

  if (this.value === 'start') {
      Array.from(animationPlayStateEle, function(ele) {
          ele.style.animationPlayState = 'running';
      });
      this.value = 'stop';
  } else if (this.value === 'stop') {
      Array.from(animationPlayStateEle, function(ele) {
          ele.style.animationPlayState = 'paused';
      });
      this.value = 'start';
  }

}, false);

然后,工作完成; 核心是,当你点击按钮和按钮的值==='停止'时,我改变了这个

    .a [class^="b"] {
        animation-play-state: play;
    }

    .a [class^="b"] {
        animation-play-state: paused;
    }
通过改变元素的样式在JavaScript中

; 当你点击按钮和按钮的值==='开始'时,我改变了这个

    .a [class^="b"] {
        animation-play-state: paused;
    }

    .a [class^="b"] {
        animation-play-state: running;
    }

清楚?