javascript - CSS 以 child 为目标但不影响它所应用的元素

标签 javascript jquery html css

这可能是一个愚蠢的问题,也许我已经起来太久了,但是有什么办法可以将类添加到元素并让它只影响子元素吗?

$('#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/

相关文章:

javascript - 文本区域中的新行在 IE 9 中不起作用

html - android浏览器(webkit)select-multiple的元素在被选中时消失

javascript - 使用 JavaScript 查找 CSS 属性的浏览器默认值

javascript - 如何在鼠标位置缩放图像并在 div 上显示结果

JavaScript:获取动态生成的对象的值

javascript - 单击事件在 jQuery Mobile 中运行不流畅

javascript - jQuery : select all element with custom attribute

jquery - 新页面打开后,事件类未保留在 mvc3 Bootstrap 导航栏中的选定列表项上

javascript - 如何在 div 上的鼠标周围插入 href - wordpress 不断删除 ahref

javascript - 如何在双引号内添加html标签