简体   繁体   中英

Rotating Background Image with jQuery

I am trying to rotate the background image of a div with jquery. It works fine but the content within the div disappears when the image rotates. How can i prevent the content from disappering and make it such the it is always present:

Code:

jQuery(document).ready(function($) {
 $(window).load(function() {           
    var i =0; 
    var images = ['http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image2.png','http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image3.png','http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image1.png'];
    var image = $('#slideit');
    image.css('background-image', 'url(http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image1.png)');
    setInterval(function(){         
        image.fadeOut(1000, function () {
        image.css('background-image', 'url(' + images [i++] +')');
        image.fadeIn(1000);
        });
        if(i == images.length)
            i = 0;
    }, 5000);            
})
});

Fiddle HERE

You can make it like this http://jsfiddle.net/frzssoyw/3/

<div id="slideit">
    <div id="slideit-bg"></div>
    <div id="slideit-content">
        some content
    </div>   
</div>

You can use position: absolute; on images.

I edited your JSFiddle using position: absolute; .

HTML :

<div id="slideit" style="width:700px;height:391px;">
    <div class="slideit-content">some content</div>
    <img class="img-rotate active" src="http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image2.png" />
    <img class="img-rotate" src="http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image3.png" />
    <img class="img-rotate" src="http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image1.png" />
</div>

CSS :

.img-rotate {
    position: absolute;
    top: 0;
    left: 0;
    width: 700px;
    height: 391px;
    opacity: 0;
    z-index: 0;
    -webkit-transition: opacity 1s linear;
    -moz-transition: opacity 1s linear;
    transition: opacity 1s linear;
}

.img-rotate.active {
    opacity: 1;
}

.slideit-content {
    z-index: 10;
    position: relative;
}

JS :

jQuery(function($) {
    var i = 0, 
        image = $('#slideit'),
        images = image.find(".img-rotate"),
        images_count = images.length,
        next_image;

    setInterval(function(){
        i = (i+1) % images_count;
        next_image = images.eq(i);
        images.filter(".active").removeClass("active");
        next_image.addClass("active");
    }, 5000);            
});

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