选择一半的元素:nth-child? [英] Selecting half the elements with :nth-child?
问题描述
以下面的代码为例:
<ul>
<li>Hello World</li>
<li>Hello World</li>
<li>Hello World</li>
<li>Hello World</li>
</ul>
可以使用:nth-child()
或否则,完全选择一半的元素总数?代码应该在上面的实例中选择第一个/最后两个 li ,然后如果我增加
li
s到六,它会选择第一个/最后三个
Is it possible, using :nth-child()
or otherwise, to select exactly half of the total elements? The code should select the first/last two li
s in the above instance, then if I were to increase the number of li
s to six, it would select the first/last three.
必须使用JavaScript ...
I feel I'm going to have to use JavaScript...
推荐答案
只有这样,你才能在到纯CSS是在 nth-child(odd)
或 nth-child(even)
。如果你想要的最后一半(而不是奇数或偶数),那么你必须使用JavaScript / jQuery。
The only way you'd be able to get anywhere near to that in pure CSS is to do a selector on either nth-child(odd)
or nth-child(even)
. If you want exactly the last half (and not either odd or even), then you'd have to use JavaScript/jQuery.
使用jQuery,你可以让他们使用:
Using jQuery, you could get them using:
var yourList = $("ul li");
yourList = yourList.slice(0, Math.floor(yourList.length/2));
这篇关于选择一半的元素:nth-child?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!