CSS动画onclick并反转下一个onclick [英] CSS animation onclick and reverse next onclick

查看:81
本文介绍了CSS动画onclick并反转下一个onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击按钮时,我正在使用精灵表和关键帧为按钮上的图像制作动画。

I am using a spritesheet and keyframes to animate the image on a button when it is clicked.

单击按钮时,我希望帧可以在同一帧中运行方向,然后将按钮保留在Spritesheet的最后一个图像上,再次单击该按钮时,我希望相同的帧向后运行,将按钮保留在Spritesheet的第一个图像上。

When the button is clicked I want the frames to run in one direction and leave the button on the last image in the spritesheet, and when it is clicked again I want the same frames to run backwards, leaving the button on the first image on the spritesheet.

我目前正在尝试使用jquery在单击按钮时将按钮上的类更改为动画类,但这似乎不起作用。

I am currently trying to use jquery to change the class on the button to an animating class when it is clicked, but this doesn't seem to be working.

小提琴: http://jsfiddle.net/CGmCe/10295 /

JS:

function animate(){
    $('.hi').addClass('animate-hi');
}

CSS:

.hi {
width: 50px;
height: 72px;
background-image: url("http://s.cdpn.io/79/sprite-steps.png");
}

.animate-hi {
    animation: play 2s steps(10);
}

@keyframes play {
   from { background-position:    0px; }
     to { background-position: -500px; }
}


推荐答案

请确保您使用的是具有动画功能的浏览器。对我来说,这在Firefox中有效。

Make sure you are using an animation-capable browser. For me this works in Firefox.

以下可能正是您想要的:

The following might be just what you wanted:

http://jsfiddle.net/CGmCe/10299/

代码:

function animateButton() {
  var button = $('.hi');
  if (button.hasClass('animate-hi')) {
    button.removeClass('animate-hi').addClass('animate-hi-reverse');
  } else if (button.hasClass('animate-hi-reverse')) {
    button.removeClass('animate-hi-reverse').addClass('animate-hi');
  } else {
    button.addClass('animate-hi');
  }
};
$(document).ready(function() {
  $('.hi').on("click", function() {
    animateButton();
  });
});

.hi {
  width: 50px;
  height: 72px;
  background-image: url("http://s.cdpn.io/79/sprite-steps.png");
}

.animate-hi {
  animation: play 2s steps(10);
}

.animate-hi-reverse {
  animation: play-reverse 2s steps(10);
}

@keyframes play {
  from {
    background-position: 0px;
  }
  to {
    background-position: -500px;
  }
}

@keyframes play-reverse {
  from {
    background-position: -500px;
  }
  to {
    background-position: 0px;
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="http://s.cdpn.io/79/sprite-steps.png" />
<button class="hi" type="button"></button>

这篇关于CSS动画onclick并反转下一个onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆