javascript中的子Div样式
我有一个预览框,可以获取颜色,然后在用户进行更改时进行更改。但是我有一个儿童部门需要changine。如何通过get元素by id选择子div? 这是我目前拥有的java脚本,如何更改它,以便让子div front更改颜色javascript中的子Div样式,javascript,css,Javascript,Css,我有一个预览框,可以获取颜色,然后在用户进行更改时进行更改。但是我有一个儿童部门需要changine。如何通过get元素by id选择子div? 这是我目前拥有的java脚本,如何更改它,以便让子div front更改颜色 document.getElementById("flip3D").style.backgroundColor=p1; #flip3D{ width:200px; height:200px; margin:20px; float:left; }
document.getElementById("flip3D").style.backgroundColor=p1;
#flip3D{
width:200px;
height:200px;
margin:20px;
float:left;
}
#flip3D > .front{
... style stuff is all there just to much toput in and worry about
}
你是说像这样的
var front = document.querySelectorAll('#flip3D .front');
for(var i=0; i<front.length; i++){
front[i].style.backgroundColor = 'red';
}
var front=document.querySelectorAll('#flip3D.front');
对于(var i=0;i您可以选择.childNodes()
和.childrends()
(谷歌将为您提供大量关于这两种方法的学习资源。)
它们将有助于在DOM中选择特定元素的子元素。我的第一个建议是使用jQuery进行这种类型的操作。它使导航DOM和更改属性更加容易
我的第二个建议是用一个类来控制这两个元素的颜色。因此,您的CSS可能如下所示:
#flip3D{
width:200px;
height:200px;
margin:20px;
float:left;
background: /*whatever you want the initial color to be*/;
}
#flip3D > .front {
/*Initial styling*/
}
#flip3D.stateChanged{
background: /*Whatever you want the new color to be*/;
}
#flip3D.stateChanged > .front {
/*New styling*/
}
然后在Javascript中更改类,如下所示:
#flip3D{
width:200px;
height:200px;
margin:20px;
float:left;
background: /*whatever you want the initial color to be*/;
}
#flip3D > .front {
/*Initial styling*/
}
#flip3D.stateChanged{
background: /*Whatever you want the new color to be*/;
}
#flip3D.stateChanged > .front {
/*New styling*/
}
jQuery示例(使用):
您也可以使用vanilla javascript进行类操作,但这要复杂得多
var ele = document.getElementById('#flip3D');
if(ele.className == 'stateChanged')
ele.className = '';
else
ele.className = 'stateChanged';
最简单的方法是使用CSS。将背景颜色更改为继承,这样他们将始终拥有其父级的颜色
.child-node {
background-color: inherit;
}
我不明白你在问什么,JS还是CSS?
.child-node {
background-color: inherit;
}