如何在单击时播放关键帧动画?

时间:2018-06-24 14:03:02

标签: javascript jquery animation css-animations keyframe

每次单击该框时,我想创建一个关键帧动画。但是,当我单击该框时,动画只能播放一次。我希望每次单击该框时动画都能正常工作。

有帮助吗? 谢谢!

    $(document).ready(function(){
        $("#rocketstart").click(function(){
            $(".rocket").css("animation-play-state", "running");
        });

    });
     
.rocket {
   background-color: red;
    width: 550px;
    height: 300px;
    cursor: pointer;
    background-repeat: no-repeat;
    margin-right: -340px;
    margin-bottom: -110px;
    animation-name: rocket;
    animation-duration: 1s;
    animation-play-state: paused;
}

@keyframes rocket {
   0%   {  transform:translate(0)    }
   100%  {  transform:translate(0, -50%) }
       70%  {  opacity:1; }
       100%  {  opacity:0; }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='rocket' id="rocketstart" title="rocketup">

1 个答案:

答案 0 :(得分:3)

不要更改动画的状态,而是将animation属性移动到新类中,并在动画末尾删除该类:

$(document).ready(function(){
        $("#rocketstart").click(function(){
            $(".rocket").addClass("animated");
        });


        $('.rocket').on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
             $(this).removeClass("animated");
        });
    });
.rocket {
   background-color: red;
    width: 550px;
    height: 300px;
    cursor: pointer;
    background-repeat: no-repeat;
    margin-right: -340px;
    margin-bottom: -110px;

}

.animated{
    animation-name: rocket;
    animation-duration: 1s;
}

@keyframes rocket {
   0%   {  transform:translate(0)    }
   100%  {  transform:translate(0, -50%) }
       70%  {  opacity:1; }
       100%  {  opacity:0; }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='rocket' id="rocketstart" title="rocketup">