开发者

jQuery Animation + background image swap

I am trying to punch above my weight with jQuery, and have run into a problem which has me stumped.

Basically, I am trying to get a truck to animate from the left hand side of the screen to the right, then when it gets to the right of the screen, the background image of the truck swaps to an image of the truck facing the other way, and it then animates back across the screen, and will repeat for ever.

I can get the truck to move across the screen, and swap the background image, but cannot get everything to happen in some sort of logical order - I.E. the truck background image is swapped on page-load and not when the left to right has completed.

Here is the code so far, and I realize that the syntax is probably开发者_如何学Go wrong, but hopefully you will see what I am trying to do:

$(document).ready(function() {

    $(".animationWrap").animate({ left: "845px" }, { duration: 9000, queue: true }){
    $(".animationWrap").css('background', 'transparent url(/Resources/Images/clearence/truckLeft.png) no-repeat 0 0');
}

});


use a callback function on the first .animate, which fires after it is complete, to do things in order (see the syntax for jQuery Animate):

$(document).ready(function() {

    $(".animationWrap").animate({ left: "845px" }, 9000, function() {
        css('background', 'transparent url(/Resources/Images/clearence/truckLeft.png) no-repeat 0 0');
        animate({ left: 0 }, 9000);
    });
});


You need to use the callback - which will get fired when the animation is complete. Sometimes it helps to create this as a named function so you can reuse it.

$(document).ready(function() {
     $('.animationWrap');.animate({ left: "845px" }, { duration: 9000, queue: true }, animationComplete ); 
});

function animationComplete(){
    $(this).css('background', 'transparent url(/Resources/Images/clearence/truckLeft.png) no-repeat 0 0');
}


This is what I did to get it working. I also used a plugin called jQuery timers to get the animation to repeat indefinately. Thanks for your help everyone.

$(document).ready(function() {
        $(".animationWrap").everyTime(0, function() {

            $(".animationWrap").animate({ left: "845px" }, 35000, function() {
            $(this).css('background', 'transparent url(/Resources/Images/clearence/truckLeft.png) no-repeat 0 0');
        });
        $(".animationWrap").animate({ left: "-1px" }, 35000, function() {
            $(this).css('background', 'transparent url(/Resources/Images/clearence/truckRight.png) no-repeat 0 0');
        });       

    });

});

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜