jQuery animation on window load on an infinite loop?

被刻印的时光 ゝ 提交于 2020-01-06 08:57:31

问题


I need a hand making this code below working. I've had it working so that when the user hovers over the image it animates up, then down when losing focus, but now I want it to run on window load on an infinite loop.

$(document).ready(function(){
    $(window).load(function(){
        $('.navImage').animate({top:'-=13'}, 700)
    }, function(){
        $('.navImage').animate({top:'+=13'}, 700);
    });
});

At the moment it's only animating 13pixels up, not down, and obviously the animation doesn't currently loop. Do I need to use some sort of callback?

Any help would be great, thanks.

[EDIT] Removed the height:toggle, didn't mean to include that.


回答1:


Try this:

function moveUp() {
    $('.navImage').animate({top:'-=13', height:'toggle'}, 700, moveDown);
}

function moveDown() {
    $('.navImage').animate({top:'+=13'}, 700, moveUp);
}

$(document).ready(function(){
    $(window).load(moveUp);
});

=== UPDATE 1 ===

function move(jElem, bUp) {
    jElem.animate(
        {top: (bUp ? '-' : '+') + '=13'},
        700,
        function() {
            move(jElem, !bUp);
        }
    );
}

$(document).ready(function() {
    $(window).load(function() {
        $('.navImage').each(function() {
            move($(this), true);
        });
    });
});

Also see my jsfiddle.

=== UPDATE 2 ===

Now they start with random delay:

function move(jElem, bUp) {
    jElem.animate(
        {top: (bUp ? '-' : '+') + '=13'},
        700,
        function() {
            move(jElem, !bUp);
        }
    );
}

$(document).ready(function() {
    $('.navImage').each(function(iIndex, jElem) {
        // get random delay
        var iTime = Math.floor(Math.random() * 700);
        setTimeout(
            function() {
                move($(jElem), true);
            },
            iTime
        );
    });
});

Also see my jsfiddle 2.

=== Update 3 ===

And in this jsfiddle additional with random speed: jsfiddle 3.




回答2:


function anim_up() {
    $('.navImage').animate({top:'-=13', height:'toggle'}, 700, anim_down)
};
function anim_down() {
    $('.navImage').animate({top:'+=13'}, 700, anim_up);
};
window.onload = anim_up;

As a sidenote, you should replace that navImage class with an ID instead, if there's only one of them.



来源:https://stackoverflow.com/questions/7636103/jquery-animation-on-window-load-on-an-infinite-loop

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