javascript - Javascript - 无法更改div background颜色

请帮助


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>

时间:

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>

或者你可以使用querySelector获得有该类的第一个元素


window.onload = function changeDivColor () {


 document.querySelector(".box").style.backgroundColor ="blue";


};



你有语法错误,方法getElementsByClassName返回数组,因此必须对要操作的元素的索引进行定位,在这种情况下,这应该可以:


window.onload = function changeDivColor () {


 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>



...