【问题标题】:CSS animation onclick and reverse next onclickCSS动画onclick和reverse next onclick
【发布时间】:2019-02-01 05:03:44
【问题描述】:

我正在使用 spritesheet 和关键帧来为按钮上的图像设置动画。

单击按钮时,我希望帧沿一个方向运行并将按钮留在精灵表中的最后一个图像上,当再次单击它时,我希望相同的帧向后运行,将按钮留在第一个精灵表上的图像。

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

小提琴: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; }
}

【问题讨论】:

  • 你需要包含不同浏览器的webkits。
  • 我弄乱了你的代码,并做了一些我自己的东西。 jsfiddle.net/CGmCe/10301
  • 是的,我知道,为了简单起见,把这些都省略了。

标签: css css-animations


【解决方案1】:

确保您使用的是支持动画的浏览器。对我来说,这适用于 Firefox。

以下可能正是您想要的:

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>

【讨论】:

  • 太好了,谢谢。正如我提到的,我希望第一次点击后的最终图像成为精灵表上的最后一张图像,我已经编辑了你的小提琴以添加它以防其他人想要它:jsfiddle.net/CGmCe/10300
【解决方案2】:

创建一个计数器变量来检查按钮是否被点击。 并基于计数器值向元素添加类,例如:

 var counter=0;
 $('.btn').on('click',function(){
  if(counter=0)
   {
     $('.hi').addClass('animate-hi');
     counter = 1;
   }
  else
   {
        counter = 0;
       $('.hi').removeClass('animate-hi');
   }
 });

确保在函数外部声明计数器变量。否则每次其值初始化为 0。

【讨论】:

猜你喜欢
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 2020-06-29
  • 2012-11-18
  • 2011-01-17
  • 1970-01-01
相关资源
最近更新 更多