How to loop .animate JQuery

2019-02-13 11:25发布

I am working with a single div with an image inside. I need the animation to scroll from right-left of the page and then comeback to the right and continue in a loop. I have looked over many posts on here but am not able to get the script working properly.

'$(document).ready(function(){
    function loop() {

       $('#clouds').animate({left: '+=1400',},50000, 'linear', function(){
           loop();
       });

HTML

< div id="clouds">< img border="0" alt="animated clouds" src="/images/clouds.png" />< /div>

CSS

#clouds {
    position:absolute;
    z-index:500;
    right:0px;
    top:10px;
}

3条回答
女痞
2楼-- · 2019-02-13 11:38

Just to add some info to others, if you're not going to use animate() you should use some setTimeout() to prevent the error Uncaught RangeError: Maximum call stack size exceeded

Example(Using jQuery):

.js

function looping() {
    $('.loader').fadeOut(1000);
    $('.loader').fadeIn(1000);
    setTimeout(function(){
        looping();
    }, 10);
}

.html

<div class='loader'>Loading...</div>
查看更多
Root(大扎)
3楼-- · 2019-02-13 11:45

Try this:

JSFiddle http://jsfiddle.net/2YqH2/

You're not moving the clouds back to the right side. Inside the loop function, I added

$('#clouds').css({right:0});

and the loop will continue from there. I also changed your animation to animate the "right" property since you said you wanted the clouds to move from right to left.

Also, your javascript was not well-formed. Make sure you get those closing braces and parentheses! Here's the fixed javascript.

$(document).ready(function() {
    function loop() {
        $('#clouds').css({right:0});
        $('#clouds').animate ({
            right: '+=1400',
        }, 5000, 'linear', function() {
            loop();
        });
    }
    loop();
});
查看更多
手持菜刀,她持情操
4楼-- · 2019-02-13 11:55

JAVASCRIPT:

$(document).ready(function() {

    $('#clouds').click(function() {
loop();       
    });

function loop(){
    alert('a');
        $('#clouds').animate({
            opacity: 0.25,
            left: '+=1400',
            height: 'toggle'
        }, 5000, 'linear', function() {
            loop();
        });

}

});

HTML:

<div id="clouds"><img border="0" alt="animated clouds" src="../img/image.png" /></div>

your error is that you are not calling the function loop never. look how it works, you can remove the alert('a') because it's just a flag to know that the cycle start over. now you need to make the reverse movement (like reset the div, to start over the movement cycle).

查看更多
登录 后发表回答