问题描述
|
使用jQuery,我想知道如何设置特定列表项的样式?
例如,我想为第一个
<li>
(第一个孩子)设置样式以赋予其自己的样式,然后为后五个列表项赋予继承人自己的样式,然后为后五个列表项赋予自己的样式,依此类推。
我很久以前读过一些关于ѭ1的东西,但不太了解。这容易实现吗?
解决方法
nth-child
允许您提供一个表达式,该表达式被评估为给出一组元素。您可以提供的最简单的表达式就是一个数字(例如nth-child(3)
),它将样式应用于第三个孩子。
您可以使用诸如3n
这样的表达式将其应用于每个第三个孩子,甚至可以使用odd
或even
将样式应用于(显然)每个奇数或偶数孩子。
但是,我认为您不能使用单一表达式将样式应用于多个元素的重复块(例如,一种样式使用5种元素,另一种样式使用另外5种元素)。
, Google提供了很多帮助:http://css-tricks.com/how-nth-child-works/
ul li:nth-child(5) {
color: #ccc;
}
或jQuery:http://api.jquery.com/nth-child-selector/
$(\"ul li:nth-child(5)\").css(\"color\",\"#ccc\");
设置LI组的样式:
$(document.body).click(function () {
$(\"ul li\").each(function (index) {
// This will get the remainder of the division of the li index by 10
var groupNum = index % 10;
// Style groups of 5 LIs differently
if (groupNum<5) {
$(this).css(\"color\",\"#ccc\");
} else {
$(this).css(\"color\",\"#222\");
}
});
});
未经测试,但是应该可以给您这个想法。