为什么我的气球不能正常飞行? Css动画翻译

时间:2014-08-01 07:11:57

标签: css3 css-animations translate3d

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

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

到目前为止,我得到了following(气球只是飞起来,不会出现/消失)。

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()时,我的动画根本无法启动。我的气球怎么可能飞?

2 个答案:

答案 0 :(得分: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
    });
});

Demo

答案 1 :(得分:0)

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

@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');
});

希望它可以提供帮助!

DEMO HERE

相关问题