我正在开发一个有32个孩子的div的项目.我需要创建一个下拉菜单,它将改变每个div和父级的背景.对于没有孩子的项目的其他部分,我一直在使用以下代码:
function changediv(color) {
document.getElementById('div1').style.background = color;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<select>
<option onClick="changediv('#555');">Hex</option>
<option onClick="changediv('blue');">Colorname</option>
<option onClick="changediv('url(example.com/example.png)');">Image</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我可以为每个孩子添加一个不同的ID(id1,id2,id3,...),但是有32个孩子,我不仅需要添加32个ID,还需要32行Javascript.一定有更好的方法; 以某种方式选择孩子甚至改变选择孩子的实际CSS代码.
谢谢,伊恩
Vij*_*wal 31
虽然这可以使用JQuery在一行中完成,但我假设您没有使用JQuery - 在这种情况下,您的代码将是:
var nodes = document.getElementById('ID_of_parent').childNodes;
for(var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style.background = color;
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅http://jsfiddle.net/SxPxN/以获取我创建的快速示例 - 点击"更改'em"以查看其中的操作
尝试使用以下代码:
var nodes = document.getElementById('ID_of_parent').getElementsByTagName("div");
for(var i=0; i<nodes.length; i++) {
nodes[i].style.background = color;
}
Run Code Online (Sandbox Code Playgroud)
如果只有一个父元素,那么我们可以querySelector用来选择该元素的所有子元素
HTML
<div class="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
Run Code Online (Sandbox Code Playgroud)
JS
let children = document.querySelector(".parent").children;
children.style.color = "red";
Run Code Online (Sandbox Code Playgroud)
如果有更多具有相同类的父元素,那么我们可以使用querySelectorAll和forEach
HTML
<div class="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div class="parent">
<div>7</div>
<div>8</div>
<div>9</div>
</div>
Run Code Online (Sandbox Code Playgroud)
JS
let children = document.querySelectorAll(".parent").children;
children.forEach(child => {
child.style.color = "red";
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53360 次 |
| 最近记录: |