我看过很多关于如何更改列表或行的背景颜色的帖子。
$('#news tbody').each(function() {
$(this).children('tr:odd').addClass('alt');
});
我明白了。但是如果我想要三行交替背景怎么办?换句话说,第一个有一种颜色,第二个有另一种颜色,第三个有另一种颜色,然后重复。我只能成功地为每三分之一添加背景颜色而不重叠。有什么建议吗?
最佳答案
您可以使用 nth-child
选择器在纯 CSS 中执行此操作:
#news tbody tr:nth-child(3n+1) {
background-color: #C00;
}
#news tbody tr:nth-child(3n+2) {
background-color: #0C0;
}
#news tbody tr:nth-child(3n+3) {
background-color: #00C;
}
或者,您可以在 jQuery 中使用数组和模运算符来实现此目的:
var classes = ['first', 'second', 'third'];
$('#news tbody tr').each(function(i) {
$(this).addClass(classes[i % classes.length]);
});
关于jquery - 如何交替列表/行的第二个和第三个背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962617/