在JavaScript中将CSS属性分配给HTML元素时出现问题

时间:2019-05-09 21:27:32

标签: javascript html

我正在尝试自己创建一个轮播(我知道有很多片段准备复制和粘贴)。我正在尝试使用setTimeout,它每4秒更改一次背景图像,但是出了点问题,但我一直无法弄清楚。我想只使用javascript找到解决方案。

这是HTML:

<div class="divi"></div>

这是Javascript:

var divi = document.querySelector(".divi");    

srcArr = ["https://picsum.photos/id/237/200/300","https://picsum.photos/id/238/200/300", "https://picsum.photos/id/239/200/300","https://picsum.photos/id/240/200/300"];    

var iter = 0;

setInterval(function () {

    if(iter == (srcArr.length)){
        return; 
    }

    else{

        divi.attributes.style.backgroundImage =  "url('" + srcArr[iter] + "')";

        console.log(divi.attributes.style.backgroundImage)

        iter++;
    }

}, 4000);

这是CSS

*{
padding: 0;
margin: 0
}

.divi{
    width: 100%;
    height: 100vh;
    background: #d3d33f;
}

您能帮助我了解我在做什么错吗?谢谢!

1 个答案:

答案 0 :(得分:2)

没有attributes属性,您应该直接使用style

divi.style.backgroundImage = ...

演示:

var divi = document.querySelector(".divi");    

srcArr = ["https://picsum.photos/id/237/200/300","https://picsum.photos/id/238/200/300", "https://picsum.photos/id/239/200/300","https://picsum.photos/id/240/200/300"];    

var iter = 0;

setInterval(function () {

    if(iter == (srcArr.length)){
        return; 
    }

    else{

        divi.style.backgroundImage =  "url('" + srcArr[iter] + "')";

        iter++;
    }

}, 4000);
*{
padding: 0;
margin: 0
}

.divi{
    width: 100%;
    height: 100vh;
    background: #d3d33f;
}
<div class="divi"></div>