每10秒更改一次图像(作为背景)

时间:2013-11-27 08:56:52

标签: javascript jquery html css

HTML

<div id="background">
     <img src="#" alt="Background Image" class="first"/>
     <img src="#" alt="Background Image" class="second"/>
</div>

我没有添加SRC,因为它会减少我的页面的加载时间。 (demo)

JQuery的

        var current = "first";
        window.setInterval(function() {
            if(current == "first") {
                $("#background .second").prop("src", getMessage());
                setTimeout(function(){
                    $("#background .second").animate({
                        opacity: 1
                    }, 1000);
                    $("#background .first").animate({
                        opacity: 0
                    }, 1000);
                },1000);
                current = "second";
            } else if (current == "second") {
                $("#background .first").prop("src", getMessage());
                setTimeout(function(){
                    $("#background .first").animate({
                        opacity: 1
                    }, 1000);
                    $("#background .second").animate({
                        opacity: 0
                    }, 1000);
                },1000);
                current = "first";
            }
            getMessage()
        }, 5000);

所以我有一个带有src链接到我的图像的数组,由function getMessage()随机选择,当显示图片时,另一个IMG标记将更改SRC并等待一两秒钟以加载该图像之后它将以动画显示。

但现在的问题是:当第一张照片的不透明度为0且第二张照片的不透明度为1时,他没有显示第二张照片。编辑:问题是图片之间的黑色淡入淡出

提前致谢!

4 个答案:

答案 0 :(得分:7)

不要使用setTimeout添加缓冲区。你不需要这个。当用户连接速度很慢时会发生什么?你的1000毫秒不会这样做。这里正确的做法是创建一个类型img的新元素。并听取onloadimage事件。触发后,您可以显示图像。

以下是此示例: Load Image from javascript

除此之外,您还需要一些CSS:

#background > img {position:absolute; top:0; left:0;}

答案 1 :(得分:1)

您需要添加以下样式,它应该可以解决您的问题:

#background > img {position:absolute; top:0; left:0;}

答案 2 :(得分:0)

尝试使用attr()函数而不是prop() 或尝试另一个:

$("#background .first").animate({
                        opacity: 1
                    }, 1000, function(){
// after finished first animation
$("#background .second").animate({
                        opacity: 0
                    }, 1000);
});

答案 3 :(得分:0)

我真的建议使用CSS进行转换。我做了一个JSfiddle - http://jsfiddle.net/9GEAn/1/并且它比你编写它的方式更有效(我建议预加载图像,即使我没有在演示中)。

window.setInterval(function () {
    current++;
    if (current>=backgrounds.length) { current=0;}
    if ($bg1.css("opacity")==1) {
        $bg2.css({
            "background-image":"url("+backgrounds[current]+")",
            "opacity":"1"});
        $bg1.css("opacity","0");
    }
    else {
        $bg1.css({
            "background-image":"url("+backgrounds[current]+")",
            "opacity":"1"});
        $bg2.css("opacity","0");
    }
}, 5000);
相关问题