简体   繁体   中英

How to Change order of background-image in javascript

I have a div with 2 images for background-image with CSS code:

background: url(img/over.png),url(img/bg.png);

With this code it first shows bg.png and then over.png

Now I want to know how I can change the order of showing the images in JavaScript dynamically?

I used this in one of my app, if you have the array of the background images that would be great

The trick behind to show image one is background-size:100% 100%, 0% 100%; and the second image is background-size:0% 100%, 100% 100%;

function sliderAnimation(ind){
    //console.log(ind);
    var slider = $('#slideout'); //#slideout is having your background images
    var l = slider.css('background-image').split(',');
    if(slider.length){
        var size = [], position = [];
        var allItemsLen = l.length;
        for(var i=0; i<allItemsLen;i++){
            if(i<ind){
                size.push('0% 100%');
                position.push('left center');
            }else if(i==ind){
                size.push('100% 100%');
                position.push('right center');
            }else if(i>ind){
                size.push('0% 100%');
                position.push('right center');
            }
        }
        if(ind==allItemsLen-1){
            size[0] = ('0% 100%');
            position[0] = ('right center');
            ind = 0;
        }else if(ind==0){
            size[allItemsLen-1] = ('0% 100%');
            position[allItemsLen-1] = ('left center');
            ind++;
        }else ind++;
        slider.css({'background-size': size.join(','),'background-position': position.join(',')});
        //when = true;
    }
    homeSLideInt = setTimeout(function(){sliderAnimation(ind)},5000);
}

call this once with sliderAnimation(0) once and it will loop every 5 seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM