我的代码出了什么问题?出于某种原因,我的函数load()不会改变.firstDiv背景?
我找不到任何错误。
function load() {
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}

.firstDiv, .secondDiv {
width: 50%;
height:100vh;
float: left;
}
.firstDiv {
background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
}

<div class="firstDiv"></div>
<div class="secondDiv">
<button onclick="load()">Change background</button>
</div>
&#13;
答案 0 :(得分:1)
在load()
函数中,需要更改它以便它使用getElementsByClassName
的第一个元素,因为它返回多个元素。
document.getElementsByClassName("firstDiv")[0]...
答案 1 :(得分:1)
如果您使用getElementByClassName
,则需要通过指定[0]
等索引来指定项目编号,或者使用id
类名称示例:
function load() {
document.getElementsByClassName("firstDiv")[0].style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}
.firstDiv, .secondDiv {
width: 50%;
height:100vh;
float: left;
}
.firstDiv {
background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
}
<div class="firstDiv"></div>
<div class="secondDiv">
<button onclick="load()">Change background</button>
</div>
ID
<div id="firstDiv"></div>
JS代码:
document.getElementById("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
答案 2 :(得分:1)
您的问题在这一行:
document.getElementsByClassName("firstDiv")...
getElementsByClassName返回文档中报告的HTMLCollection。
您需要使用以下内容更改该行:
document.getElementsByClassName("firstDiv")[0]
摘录:
function load() {
document.getElementsByClassName('firstDiv')[0].style.backgroundImage
= "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}
&#13;
.firstDiv, .secondDiv {
width: 50%;
height:100vh;
float: left;
}
.firstDiv {
background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
}
&#13;
<div class="firstDiv"></div>
<div class="firstDiv"></div>
<div class="secondDiv">
<button onclick="load()">Change background</button>
</div>
&#13;