如何在某个div上应用动画? [英] How to apply animation on a certain div?

查看:53
本文介绍了如何在某个div上应用动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的着陆页很长.我想应用动画(使汽车在道路上行驶).具有道路背景的div大约在我的着陆页的中间(我必须向下滚动9次),我找到了在GSAP JS的帮助下为汽车运动设置动画的方法.但是我不知道如何仅当视口将div对准道路时才能使动画工作.我试图搜索特定的事件",但是找不到.您能帮我找到解决问题的办法吗?

I have a very long landing page.I want to apply the animation(To make the car move on the road). The div with the background of the road is approximately in the middle of my landing page(I have to scroll down the page 9 times) I found the way to animate the movement of a car with the help of GSAP JS. But I have no idea how to make my animation work only when my viewport is focusing the div with the road. I tried to search for a particular "event", but I failed to find it. Can you help me to find the soluton of my problem?

$(document).ready(function(){
TweenMax.to(document.getElementById("car"), 5, {bezier:{type:"cubic", values:
[{x:100, y:250}, {x:400, y:0}, {x:300, y:500}, {x:500, y:400}], 
autoRotate:["x","y","rotation", 0, true]}, ease:Power1.easeInOut});
});

推荐答案

正如评论中提到的,一种方法是侦听 scroll 事件并比较窗口和窗口的位置.元素.

As has been mentioned in the comments, one approach is to listen to the scroll event and compare the position of the window and the element.

这是一个粗糙的例子.请注意,我更改了汽车的动画设置;您可以将其替换为您的功能.还有两件事:我的代码仅对汽车进行一次动画处理,并且一旦用户滚动离开该元素就不会停止动画.您可以根据需要调整这些内容.

Here is a rough example. Please note that I changed how the car is animated; you can substitute it with your function. Two more things: my code only animates the car once and it does not stop the animation once the user scrolls away from the element. You can adjust these things as per your needs.

function AnimateIfUserHasSeenCar() {
    if ($(window).scrollTop() + $(window).height() > $("#car").position().top) {
        $("#car").addClass("go"); //Replace this with how you create the anitmation
    }
}

$(document).ready( AnimateIfUserHasSeenCar );
$(document).scroll( AnimateIfUserHasSeenCar );

/* All these CSS rules should be unnecesary for you. They are either for the animation or to set up the position of the car */
 .spacer {
    height:1000px;
}
#car {
    transition: transform 2s;
    height:120px;
    width:150px;
}
#car img {
    width:100%;
}
#car.go {
    transform:translatex(400px);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="spacer"></div> <!-- This is just to cause the #car to be offscreen at first -->
<div id="car">
    <img src="http://fc06.deviantart.net/fs70/f/2010/321/d/e/my_lego_car_side_veiw_by_kotetsuninja-d332j6f.png" />
</div>

这篇关于如何在某个div上应用动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆