問(wèn)題描述
以下面的代碼為例:
<ul>
<li>Hello World</li>
<li>Hello World</li>
<li>Hello World</li>
<li>Hello World</li>
</ul>
是否有可能,使用 :nth-child()
或其他方式,準(zhǔn)確選擇總元素的 一半?代碼應(yīng)該在上面的實(shí)例中選擇第一個(gè)/最后一個(gè) 兩個(gè) li
s,然后如果我將 li
s 的數(shù)量增加到六個(gè),它將選擇第一個(gè)/最后一個(gè)三個(gè).
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.
我覺(jué)得我將不得不使用 JavaScript...
I feel I'm going to have to use JavaScript...
推薦答案
在純 CSS 中接近的唯一方法是在任一 nth-child(odd)
或 nth-child(even)
.如果你想要準(zhǔn)確的后半部分(而不是奇數(shù)或偶數(shù)),那么你必須使用 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));
這篇關(guān)于用 :nth-child 選擇一半的元素?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!