css - 在另一个 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
(不使用id
s)?
我想要达到的目标:
#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>
但是有没有办法一个一个地选择#container
div 中的每个元素,而不管它的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;
}
解决方案
如果您尝试仅使用 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
推荐阅读
- c# - Internet Explorer 中的 WPF XBAP DPI 缩放
- javascript - Gulp Concat + Uglify 订单 JS 错误
- java - 在 Spring Boot 控制器中使用 GraphQL API
- php - 在 MySQL 数据库中创建用户
- jenkins - 如何在 Jenkins 共享库函数中存储/取消存储文件
- delphi - Delphi 只复制具有特定扩展名的文件
- cordova - 单击cordova android中的下拉菜单
- python - Python 替换 || 具有 CONCAT 功能的运算符
- unix - 使用 sed 替换通配符
- angular - 如何正确过滤角度数组