How to apply animation on a certain div?

放肆的年华 提交于 2021-02-11 12:36:00

问题


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

回答1:


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>



回答2:


Made a quick car moving jsFiddle using TweenMax animation.Refer jsFiddle Code. Hope it helps.

HTML:

<div id="car"> <img src="http://fc06.deviantart.net/fs70/f/2010/321/d/e/my_lego_car_side_veiw_by_kotetsuninja-d332j6f.png" style="height:200px;width:250px;"/></div>

<button id="chk">play</button>

JS:

$("#chk").on('click',function(){
    carplay();
});


来源:https://stackoverflow.com/questions/27404535/how-to-apply-animation-on-a-certain-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!