简体   繁体   English

单击按钮即可获得CSS动画

[英]CSS animation on click of a button

Here is the plunker 这是the

$(document).ready(function(){
  $('#btn-animate').click(function(){
    animate();
  });
  $('#btn-remove').click(function(){
    $('.to-animate').removeClass('animate');
  });

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

Here if I click on "ANIMATE" button it adds an 'animate' class to the div and animates it(changes color). 在这里,如果我单击“动画”按钮,它将为div添加一个“动画”类并对其进行动画处理(更改颜色)。 But if you click again it tries to remove the class 'animate' and add it back so that the animation triggers again. 但是,如果再次单击,它会尝试删除“动画”类并将其重新添加,以便动画再次触发。

But it is not happening. 但这没有发生。 Strangely if I click the "REMOVE" button to remove the 'animate' class and then with the "ANIMATE" button add the class it animates again. 奇怪的是,如果我单击“删除”按钮以删除“动画”类,然后使用“动画”按钮添加该类,则它将再次进行动画处理。

Can anyone explain why first button is failing to give the required result? 谁能解释为什么第一个按钮无法提供所需的结果? And how can I get the animation be triggered every time I click the "ANIMATE" button? 每次单击“动画”按钮时如何触发动画?

Typically browsers don't repaint the UI until after all javascript has finished running and most browsers are smart enough to figure out that after the second click of the animate button the DOM is the same before and after and so it doesn't do anything. 通常,浏览器直到所有javascript完成运行后才重绘UI,并且大多数浏览器足够聪明,以至于在第二次单击动画按钮之后,DOM前后都是相同的,因此它不会执行任何操作。

Easiest solution is to remove the class then set a timeout to add it back after a short delay. 最简单的解决方案是删除该类,然后设置一个超时时间,以在短暂的延迟后将其重新添加。

function animate(){
    $('.to-animate').removeClass('animate');
    setTimeout(function(){$('.to-animate').addClass('animate');}, 10);
}

Man, from what I see, everything is working normal, I opened the link and there it is also working normal. 老兄,据我所知,一切都正常,我打开了链接,那里也正常。

What if you check if the class exists instead of remove? 如果您检查类是否存在而不是删除,该怎么办?

function animate(){
    if(!$('.to-animate').hasClass('animate')){
        $('.to-animate').addClass('animate');
    }
}

jQuery already has the class for your need. jQuery已经有了您需要的类。 It is called toggleClass 它称为toggleClass

$(document).ready(function() {
  $('#btn-animate,#btn-remove').click(function() {
    $('.to-animate').toggleClass('animate');
});

Instead of getting the animation from a class, just do the animation with jquery 无需从类中获取动画,只需使用jquery进行动画处理

$(document).ready(function(){
  $('#btn-animate').click(function(){
    $(this).animate(
    "opacity":"0",
    // whatever animation you want in here
    }, 300);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM