背景不会改变onclick功能

时间:2017-07-06 19:26:20

标签: html css onclick

我的代码出了什么问题?出于某种原因,我的函数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;
&#13;
&#13;

3 个答案:

答案 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

  1. 分配ID,例如<div id="firstDiv"></div>
  2. 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]

摘录:

&#13;
&#13;
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;
&#13;
&#13;