我进行了一些搜索/谷歌搜索,但没有找到任何结果。这是我的问题,我有以下 html 结构(只是一个示例,列表的长度是动态的):
<ul class="collection">
<a class="collection-item head">Alvin</li>
<a href="#" class="collection-item">Alvin</a>
<a href="#" class="collection-item">Alvin</a>
<a href="#" class="collection-item">Alvin</a>
<a class="collection-item head">Alvin</li>
<a href="#" class="collection-item">Alvin</a>
<a href="#" class="collection-item">Alvin</a>
<a href="#" class="collection-item">Alvin</a>
<a class="collection-item head">Alvin</li>
<a href="#" class="collection-item">Alvin</a>
<a href="#" class="collection-item">Alvin</a>
<a href="#" class="collection-item">Alvin</a>
</ul>
我想要这样的 CSS:http://i.imgur.com/iip6VXt.png
我对所有 .head 类使用 css 选择器来更改它们的边框颜色:
.collection .head:nth-child(1){
border-left: 5px solid green;
}
.collection .head:nth-child(2){
border-left: 5px solid orange;
}
.collection .head:nth-child(3){
border-left: 5px solid blue;
}
它适用于 .collection 的第一个 child ,但第二个和第三个没有改变。我发现 css 选择器计算所有 .collection 的子类而不仅仅是 .head 类。
所以我被困在那里了。有谁知道这种情况吗?
我从 Saqib Amin 那里得到了一个很好的答案,但我无法让它发挥作用。所以我制作了一个完整的 jquery 版本。希望对大家有用。
$('.head').each(function(index) {
switch (index) {
case 0:
$(this).css({
property1: 'value1',
property2: 'value2'
});
break;
case 1:
$(this).css({
property1: 'value1',
property2: 'value2'
});
break;
case 2:
$(this).css({
property1: 'value1',
property2: 'value2'
});
break;
}
});
最佳答案
你为 nth-child 选择器提供了错误的值,你的 CSS 应该是这样的:
.collection .head:nth-child(1){
border-left: 5px solid green;
}
.collection .head:nth-child(5){
border-left: 5px solid orange;
}
.collection .head:nth-child(9){
border-left: 5px solid blue;
}
要了解有关第 n 个子选择器如何工作的更多信息,请访问:https://developer.mozilla.org/en/docs/Web/CSS/:nth-child
正如您所说,元素的数量可能会有所不同,因此您应该使用不同的解决方案,我建议使用 jQuery 为每个 .head
元素添加索引号,然后使用该索引设置元素的样式。
您的 jQuery 代码将是:
var counter = 1;
$('.head').each(function() {
$(this).attr('data-index', counter++);
});
然后你的 CSS 会是这样的:
.collection .head[data-index=1] {
border-left: 5px solid green;
}
.collection .head[data-index=2] {
border-left: 5px solid orange;
}
.collection .head:[data-index=3] {
border-left: 5px solid blue;
}
关于jquery - Css 选择器没有像我预期的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34823808/