jQuery Animation + background image swap

2019-07-24 04:04发布

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 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');
}

});

3条回答
虎瘦雄心在
2楼-- · 2019-07-24 04:36

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);
    });
});
查看更多
孤傲高冷的网名
3楼-- · 2019-07-24 04:49

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');
        });       

    });

});

查看更多
祖国的老花朵
4楼-- · 2019-07-24 04:59

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');
}
查看更多
登录 后发表回答