这可能是一个愚蠢的问题,也许我已经起来太久了,但是有什么办法可以将类添加到元素并让它只影响子元素吗?
$('#add').click(function(){
$('.parent').append("<div class='child'></div>");
});
$('#bg').click(function(){
$('.child').css('background-color', 'orange');
});
.parent {
background-color:yellow;
border: 2px solid black;
height:200px;
width: 300px;
}
.child {
height:15px;
width:280px;
border: 1px solid black;
margin-top:10px;
margin-bottom:10px;
margin-left:5px;
background-color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
<button id='add'>Add another</button><button id='bg'>Change Background</button>
<div class='child'></div>
<div class='child'></div>
<div class='child'></div>
</div>
引用代码片段,我需要父 div 背景颜色保持白色,但我需要更改 css 以便它影响所有 future 动态创建的 div。
最佳答案
添加一个类到.parent
div 并让它影响 child :
$('#add').click(function() {
$('.parent').append("<div class='child'></div>");
});
$('#bg').click(function() {
$('.parent').addClass('orange-bg');
});
.child {
height: 15px;
width: 280px;
border: 1px solid black;
margin-top: 10px;
margin-bottom: 10px;
margin-left: 5px;
background-color: white;
}
.parent {
background-color: yellow;
border: 2px solid black;
height: 200px;
width: 300px;
}
.parent.orange-bg .child {
background-color: orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
<button id='add'>Add another</button>
<button id='bg'>Change Background</button>
<div class='child'></div>
<div class='child'></div>
<div class='child'></div>
</div>
关于javascript - CSS 以 child 为目标但不影响它所应用的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841032/