Javascript代码不会交叉淡入淡出



我有一些Javascript代码,我从codependency .io。但是我很难执行它,尽管它是完全相同的代码。我只是在学习Javascript,所以我是一个初学者。我没有用HTML,我只用了CSS &Javascript。背景图像可以随机播放,但是渐变不起作用。

下面是我的CSS代码片段:
body {
    margin: 0;
    background-image: url(/image1.jpg) no-repeat center center fixed;
    background-size: cover;
    margin: 0;
    width: 100%;
    height: 100%;
    transition: 1s;
}

这是与之配套的JS。

var bgImageArray = ["image2.jpg", "image3.jpg", "image4.jpg"],
base = "/",
secs = 4;
bgImageArray.forEach(function(img){
    new Image().src = base + img; 
    // caches images, avoiding white flash between background replacements
});
function backgroundSequence() {
    window.clearTimeout();
    var k = 0;
    for (i = 0; i < bgImageArray.length; i++) {
        setTimeout(function(){ 
            document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
            document.documentElement.style.backgroundSize ="cover";
        if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }            
        }, (secs * 1000) * i)   
    }
}
backgroundSequence();

任何帮助都将非常感激!

我认为问题是你定义了CSS规则的body,但在你的JavaScript,新的图像附加到documentElement,这是等于html标签,而不是body标签。

试着改变这些行:

document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";

:

document.body.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.body.style.backgroundSize ="cover";

documentElement改成body

您应该将document.documentElement更改为document.body,您可以删除window.clearTimeout

你可以看到这个演示工作:

http://codepen.io/dangvanthanh/pen/NGpqYr

最新更新