2

我正在尝试使用 CSS translate 执行以下操作:

单击按钮时,气球会出现并飞走。当它们完成飞行时,它们会消失并返回到起始位置(这样下次单击按钮时会发生相同的行为)。

到目前为止,我得到了以下信息(气球只是飞起来,没有出现/消失)。

HTML

<div>
    <img class="object" src="http://pngimg.com/upload/balloon_PNG580.png" />
</div>
<br><br><button id="button">Fly!!!</button>

CSS

div{
    height: 300px;
    position: relative;
}
.object {
    width: 60px;
    position: absolute;
    bottom: 0;
    -webkit-transition: all 1s ease-in-out;
    -moz-transition:    all 1s ease-in-out;
    -o-transition:      all 1s ease-in-out;
}
.move-up{
    transform:         translate(0,-150px);
    -webkit-transform: translate(0,-150px);
    -o-transform:      translate(0,-150px); 
    -moz-transform:    translate(0,-150px);
}

JS

$('#button').click(function(){
    $('.object').addClass('move-up');
});

问题是,当我尝试添加开始display : none对象并单击添加$('.object').show()时,我的动画根本没有开始。如何让我的气球飞起来?

4

2 回答 2

2

您可以使用 CSS3 动画来实现此效果。有关每个项目的更多详细信息,请参阅内联注释。

CSS:

.object {
    width: 60px;
    position: absolute;
    bottom: 0;
    opacity: 0; /* make the balloon invisible on load and once animation is complete */
}

.move-up{
    -webkit-animation: balloon 1s linear; /* the animation to move up */
    -moz-animation: balloon 1s linear;
    animation: balloon 1s linear;
}

@keyframes balloon { /* included only unprefixed version to keep answer short, demo has the prefixed versions also */
    5% {
        transform: translate(0, 0); /* keep at original position */
        opacity: 1; /* make opacity as 1 after a short time for balloon to appear */
    }
    50% {
        transform: translate(0, -150px); /* move up */
        opacity: 1; /* retain the opacity */
    }
    55%, 100% {
        transform: translate(0, -150px); /* retain translated position till end */
        opacity: 0; /* hide the ballons and make it hidden for the rest of the duration */
    }
}

jQuery:

$('#button').click(function(){
    $('.object').addClass('move-up'); // adding the move up animation class to make it move
    $('.object.move-up').on('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd',function(){
        $('.object').removeClass('move-up'); // removing the animation class on animation end to make it come back to original state
    });
});

演示

于 2014-08-01T07:57:36.307 回答
0

我在动画中使用 translate 属性制作了一个 codepen。(我的容器高度为 700 像素)。

@keyframes moveballoon { 
  0% {  transform: translate(0px, 700px);}
  100% { transform: translate(0px, -1200px);} 
}

.animationballoon { 
  animation: moveballoon 2s infinite linear forwards;
}

使用 Jquery,你可以有类似的东西:

$('#button').click(function(){
$('.object').addClass('animationballoon');
});

希望它可以帮助!

在这里演示

于 2015-11-03T11:56:14.653 回答