我遇到了一个问题,我无法“访问”这个 div 的子元素:
<style type="text/css">
div#memory_board{
background:#CCC;
border:#999 1px solid;
width:800px;
height:540px;
padding:24px;
margin:0px auto;
}
div#memory_board > div{
background: url(http://image.png) no-repeat center;
border:#000 1px solid;
width:71px;
height:71px;
float:left;
margin:10px;
padding:20px;
font-size:64px;
cursor:pointer;
text-align:center;
}
</style>
我想做的是用一个按钮改变所有 div#board > div
的背景。
我试过这个:
function imageChange(){
document.getElementsByTag("memory_board").style.background="url(http://image.png)";
}
当然,这行不通。我尝试了各种组合,但似乎没有任何效果。有小费吗? (我确实有一个稍后调用函数的按钮,所以这绝对不是问题!)
这是完整的代码: https://jsfiddle.net/o72z8dqv/
更新: 已解决,谢谢! Here是更新后的工作代码。
最佳答案
您可以使用querySelectorAll
然后您需要使用循环来改变每个子div
的样式,因为它返回NodeList
function imageChange() {
var divs = document.querySelectorAll("#board > div");
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundImage = "url('http://placehold.it/350x150/333333')";
}
}
div#board > div {
background: url('http://placehold.it/350x150/ffffff') no-repeat center;
border: #000 1px solid;
width: 71px;
height: 71px;
float: left;
margin: 10px;
padding: 20px;
font-size: 50px;
text-align: center;
}
<button onclick="imageChange()">BUtton</button>
<div id="board">
<div>Div</div>
<div>Div</div>
</div>
您还可以使用 Array.from()
或 Array.prototype.slice.call()
然后你可以使用 forEach
循环
关于javascript - 如何更改div的子内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37114520/