用jQuery旋转背景图像

时间:2014-11-27 13:50:26

标签: javascript jquery html css

我正在尝试使用jquery旋转div的背景图像。它工作正常,但div中的内容在图像旋转时消失。我如何防止内容消失,并使其始终存在:

代码:

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

小提琴HERE

2 个答案:

答案 0 :(得分:0)

你可以像http://jsfiddle.net/frzssoyw/3/

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

答案 1 :(得分:0)

您可以在图片上使用position: absolute;

我使用position: absolute;编辑了 JSFiddle

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