Animating a div up and down repeatedly

2019-03-02 13:14发布

问题:

I would like to have a div that moves up and down repeatedly using jquery. In other words, the div starts at the top of some location, moves down and then moves back up and repeats this, in about a 1 second interval from going from top to bottom and 1 second back to the top. There's the slideUp and slideDown as well as animate methods but I'm not sure how to accomplish this since it needs to be in an endless loop and in javascript you must avoid such loops.

回答1:

jQuery's animate logic can safely be called with callbacks or chained together without using setTimeout/setInterval:

Something like this should work just fine for you

Demo

function loop() {
    $('.bouncer').animate({'top': '500'}, {
        duration: 1000, 
        complete: function() {
            $('.bouncer').animate({top: 0}, {
                duration: 1000, 
                complete: loop});
        }});
}
loop();


回答2:

use setInterval, see here: http://www.w3schools.com/js/js_timing.asp

so try this

Javascript

$(document).ready(function() {
    setInterval(function() {
        $('#thediv').slideUp('500', function() {
            $('#thediv').slideDown('500');
        });
    }, 1000);
});

HTML

<div id='thediv' style='width:100px;height:200px;border:1px solid black;'>
Div Contents
</div>

you may need to tweak the timings (which are in miliseconds)