jquery simple animate/rotate of a css background-image inside a div?

谁说我不能喝 提交于 2019-12-02 03:20:56

Something like this should do the trick?

jQuery( function( $ ) {
    var images = [ "bg-1.jpg", "bg-2.jpg", "bg-3.jpg", "bg-4.jpg", "bg-5.jpg" ];
    var currentImage = 0;

    function changeBackground() {
        $( '#page_bg' ).css( { backgroundImage: 'url(' + images[ ++currentImage ] + ')' } );
        if ( currentImage >= images.length - 1 ) {
            currentImage -= images.length;
        }
    }

    setInterval( changeBackground, 5000 );  
});

If those are the actual image names, you really wouldn't need an Array.

  // cache the element
var $page_bg = $('#page_bg');

setInterval( function() {
    $page_bg.css( 'background-image', function(i,bg) {
       return bg.replace(/\d/, function(str) { return (str % 5) + 1;});
    });
}, 5000);

In the return (str % 5) + 1; part, the number 5 represents the total number of images. They should be sequentially indexed starting with 1 like yours are.


EDIT: Or if there will be a number elsewhere in the URL, then do this instead:

  // cache the element
var $page_bg = $('#page_bg');

setInterval( function() {
    $page_bg.css( 'background-image', function(i,bg) {
       return bg.replace(/(\d)(\.jpg)/, function(str,p1,p2) { return ((p1 % 5) + 1) + p2;});
    });
}, 5000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!