Easiest way to animate background image sliding left?

瘦欲@ 提交于 2019-12-04 21:18:00

As soon as I posted this I figured it out. In case it helps anyone else, here's the function I came up with:

function animateBar(self) {
    // Setup
    var bar = self.element.find('.ui-progress-bar');

    bar.css('background-position', '0px 0px');

    bar.animate({
        backgroundPosition: '-20px 0px'
    }, 1000, 'linear', function() {
        animateBar(self);
    });
}

Just a suggestion, but rather than using a standard function and passing in the element as an argument, it would be better to use fn.extend.

$.fn.extend({
    animateBar: function(){
       $(this).find('.ui-progress-bar').css('background-position', '0px 0px');
       $(this).find('.ui-progress-bar').animate({
            backgroundPosition: '-20px 0px'
       }, 1000, 'linear', function() {
            animateBar(self);
       });
    }
});

Then you would call the function like this:

$(this).animateBar(); 

vs

 animateBar( $(this) );

Just my 2 cents. However @Markus 's Gif solutions is definitely superior, unless you have a specific reason to use an image animated by jQuery. Also your solution will not loop on its own.

I'd say a better solution in your case (animating a progress bar) is to use an animated .gif as the progress bar's background-image.

Also, to switch from a static progress bar to an animated one, just use something like:

$("#progress").css("background-image", "progress.gif");

You can use the Spritely plugin , and for your case of animating a sliding background and repeating it, you can use the pan() method which makes the background image pan continually to the left or right and then repeat.

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