简体   繁体   中英

How do I make a div element repeat its animation?

Basically, I have a purple box. I want to animate it and make it move left by 250px, and i want it to then move down by 50px, then go right, and repeat that cycle. Here is what i have so far :

<!DOCTYPE html>
<html>
<body>

<div id="goodbox"  style="height:50px;width:40px;background-color:purple;position:absolute"> </div>


<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">
 </script>

<script>
 $(document).ready(function(){
 $("#goodbox").animate({left:"300px"},5000)
$("#goodbox").animate({bottom:"300px"},5000)
})
 </script>



 </body>
 </html>

You see after it animates left, it then moves to the bottom of the screen and then animates, but i want it to move from where it left off. So basically: move left 250px; move down 20px; move right 250px; move up 20px; then to repeat

How do I do this? And lets just say I have this other blue box. Lets say I give this box functions, so if i press the left key it'll move left, right key right. down key down and up key up. How could i then make the purple box stop moving if these two boxes make contact. Thanks in advance to anyone willing to answer this.

You can encapsulate the animation code in a normal function and pass it in the complete callback of the last call of animate function. Take a look at How can I loop an animation continuously in jQuery? for more information.

You can use relative positioning in animate. So instead of setting the exact left or bottom, you can specify that it moves the 250px that you want. To do this you use:

$('#goodbox').animate({'left': '-=250px'}, 5000);

To get it to animate one after another, you can use the the 3rd parameter of the animate() method to provide a callback that happens after the animation has finished. For example:

$('#goodbox').animate({'left': '-=250px'), 5000, function() {
    $('#goodbox').animate({'top: '+=20px'}, 5000, function() { ... });
});

To then get this to repeat you can use window.setInterval() . This allows you to run a piece of javascript every x milliseconds. So lets say you have 4 animations each lasting 5 seconds you need to have the setInterval() running every 20 seconds. So you would do this:

window.setInterval(animations, 20000);

function animations() {
    // All your animation code here
}

Hopefully I've given you enough information to get started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM