无法更改div背景颜色

时间:2019-06-15 01:50:22

标签: javascript html css

我正在尝试通过页面加载中带有javascript的类“ box”来更改div的背景颜色。我正在使用getElementsByClassName更改文档,但是在加载页面时没有任何反应。我已经检查过错别字并研究了互联网,但实际上无法弄清楚这一点……而且它也是如此简单。

请帮助

window.onload = function changeDivColor () {
  document.getElementsByClassName("box").style.backgroundColor = "blue";
};
.box {
  background-color: red;
  display: flex;
  align-items: center;
  justify-content: center;
  vertical-align: middle;
  margin: 5px;
  border-radius: 5%;
}
<html>

<link rel="stylesheet"
  type="text/css"
  href="/Users/skyler/Documents/GitHub/Code/style.css"/>

<script src="javascript.js"> </script>



  <div class="container">
    <div class="box"> <label> <input type="checkbox"> <div class="label-text"></div> </label> </div>
    
  </div>
  
</html>

4 个答案:

答案 0 :(得分:3)

document.getElementsByClassName返回一个数组,您需要为第一项获得索引0

document.getElementsByClassName("box")[0].style.backgroundColor = "blue";

window.onload = function changeDivColor () {
  document.getElementsByClassName("box")[0].style.backgroundColor = "blue";
};
.box {
  background-color: red;
  display: flex;
  align-items: center;
  justify-content: center;
  vertical-align: middle;
  margin: 5px;
  border-radius: 5%;
}
<html>

<link rel="stylesheet"
  type="text/css"
  href="/Users/skyler/Documents/GitHub/Code/style.css"/>

<script src="javascript.js"> </script>



  <div class="container">
    <div class="box"> <label> <input type="checkbox"> <div class="label-text"></div> </label> </div>
    
  </div>
  
</html>

答案 1 :(得分:2)

或者,您可以使用querySelector来获取该类的第一个元素

window.onload = function changeDivColor () {
    document.querySelector(".box").style.backgroundColor = "blue";
};

答案 2 :(得分:0)

您遇到语法错误。方法 getElementsByClassName返回一个数组,因此您必须定位要操作的元素的索引。在这种情况下,它应该起作用:

window.onload = function changeDivColor () {
 document.getElementsByClassName("box")[0].style.backgroundColor = "blue";
};

答案 3 :(得分:0)

使用

window.onload = function changeDivColor () {
  document.getElementsByClassName("box")[0].style.backgroundColor = "blue";
};
.box {
  background-color: red;
  display: flex;
  align-items: center;
  justify-content: center;
  vertical-align: middle;
  margin: 5px;
  border-radius: 5%;
}
<html>

<link rel="stylesheet"
  type="text/css"
  href="/Users/skyler/Documents/GitHub/Code/style.css"/>

<script src="javascript.js"> </script>



  <div class="container">
    <div class="box"> <label> <input type="checkbox"> <div class="label-text"></div> </label> </div>

  </div>

</html>