首页 > 解决方案 > 在另一个 CSS 选择器之后选择一个 div

问题描述

我一直在尝试这样做一段时间,觉得它应该相当简单:

<div id = "container">
  <div id = "item1" class = "item"> </div>
  <div id = "item2" class = "item"> </div>
  <div id = "item3" class = "item"> </div>
</div>

如何一个接一个地选择每个项目并为每个项目分配不同的background(不使用ids)?

我想要达到的目标:

#item1 {
  background: red;
}

#item2 {
  background: blue;
}

#item3 {
  background: yellow;
}
<div id="container">
  <div id="item1" class="item"> </div>
  <div id="item2" class="item"> </div>
  <div id="item3" class="item"> </div>
</div>

但是有没有办法一个一个地选择#containerdiv 中的每个元素,而不管它的id值是多少?通过执行以下操作:

.container:nth-child(1){ /*select first child of .conainter (#item1) ?*/
background: red;
}

或者

.item:nth-of-type(2){ /*select second element of type .item (#item2) */
background: blue;
}

标签: csscss-selectors

解决方案


如果您尝试仅使用 CSS 执行此操作:

.item:nth-of-type(1) { background: #fff}
.item:nth-of-type(2) { background: #000}
.item:nth-of-type(3) { background: #abc}

如果你想在事后使用 JS 和/或 jQuery 来获取这些:

jQuery(".item").each(function(i, el) {
   if(i == 0) {
      el.style.backgroundColor = "black";
   } else {
      el.style.backgroundColor = "red";
   }
})

i这将是您的.item元素的索引,因此您可以通过该索引定位您需要的元素(因此是有条件的)

另请注意,.item如果您想查看背景颜色的变化,您需要在元素上设置高度或添加一些内容。默认高度为0


推荐阅读