Change paused animation's play state to running on click of a link

99封情书 提交于 2019-12-13 15:25:55

问题


Using CSS and Javascript (preferably not jQuery as I don't understand as well) how do I set a CSS animation to go from a pause state to a play state triggered when the user clicks a text link (href) as opposed to a button?


回答1:


It is very simple. Just set the animation-play-state to paused initially and then add a class which sets the animation-play-state to running when the anchor link is clicked.

Add a return false to the event handler to prevent the default action of the anchor from happening.

window.onload = function() {
  var els = document.getElementsByClassName("play-link");
  for (var i = 0; i < els.length; i++) {
    els[i].addEventListener('click', function(e) {
      e.target.previousElementSibling.classList.add('play');
      return false;
    });
  }
}
div {
  animation: shake 1s infinite;
  animation-play-state: paused;
  border: 1px solid;
  width: 200px;
  height: 100px;
}
@keyframes shake {
  from {
    transform: translateX(0px);
  }
  to {
    transform: translateX(200px);
  }
}
div.play {
  animation-play-state: running;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='animate'>Some text</div>
<a href='#' class='play-link'>Play</a>
<div class='animate'>Some text</div>
<a href='#' class='play-link'>Play</a>

You can even toggle between paused and running states by toggling the play class on and off.

window.onload = function() {
  var els = document.getElementsByClassName("play-link");
  for (var i = 0; i < els.length; i++) {
    els[i].addEventListener('click', function(e) {
      e.target.previousElementSibling.classList.toggle('play');
      return false;
    });
  }
}
div {
  animation: shake 4s infinite;
  animation-play-state: paused;
  border: 1px solid;
  width: 200px;
  height: 100px;
}
@keyframes shake {
  0% {
    transform: translateX(0px);
  }
  50% {
    transform: translateX(400px);
  }
  100% {
    transform: translateX(0px);
  }  
}
div.play {
  animation-play-state: running;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='animate'>Some text</div>
<a href='#' class='play-link'>Toggle Play State</a>
<div class='animate'>Some text</div>
<a href='#' class='play-link'>Toggle Play State</a>


来源:https://stackoverflow.com/questions/32825156/change-paused-animations-play-state-to-running-on-click-of-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!