开发者

jQuery hover that changes various backgrounds with infinite loop until mouse is out

I've a <div> with a background-image that will cha开发者_Go百科nge the background 4 times with a delay of 300ms. I've tried with setTimeout which seems to work correct, but clearTimeout(t); when the mouse moves out fails because the backgrounds continue changing.

$(document).ready(function() {
    $(".image").hover(function(){
        var obj = $('.image');
        $(this).css("background-position", "0 -90");
        var t=setTimeout(function(){obj.css("background-position", "0 -180")}, 300);
        var t=setTimeout(function(){obj.css("background-position", "0 -270")}, 600);
        var t=setTimeout(function(){obj.css("background-position", "0 -360")}, 900);
    }, function() {
        $(this).css("background-position", "0 0");
        clearTimeout(t);
    });
});

I would like too to insert to the hover function a way to have a infinite loop until the mouse is released.

Sorry for my school English.

Thanks in advance!


move the t var dec outside of the function. then it will be in the closure.

eg something like this:

$(document).ready(function() {
    var t1,t2,t3;

    $(".image").hover(function(){
        var obj = $('.image');
        $(this).css("background-position", "0 -90");
        var t1=setTimeout(function(){obj.css("background-position", "0 -180")}, 300);
        var t2=setTimeout(function(){obj.css("background-position", "0 -270")}, 600);
        var t3=setTimeout(function(){obj.css("background-position", "0 -360")}, 900);
    }, function() {
        $(this).css("background-position", "0 0");
        clearTimeout(t1);
        clearTimeout(t2);
        clearTimeout(t3);
    });
});

There are other issues with this code but I'm just answering the question.


Because with this the variable t is overwritten twice by the two previous setTimeouts, so only the code for the last setTimeout is preserved, so when you call clearTimeout you're only clearing the last setTimeout.

What you can do is to use three different variables to store this, change to setInterval instead, or use a loop to set the timeouts.


Have you tried jquery's animate? Would probably simplify things a lot -- they'll deal with all the timers and stuff for you. It's baked into the library you're already using so why not take advantage of it?

$('.image').mouseover(function(){
    $(this).stop().animate(
        {backgroundPosition:"(0 -360px)"}, 
        {duration:1800})
    })
.mouseout(function(){
    $(this).stop().animate(
        {backgroundPosition:"(0 0)"}, 
        {duration:100})
    });

By default it's going to use a liniar animation, but you could set up different easing if you wanted something different.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜