問題描述
假設你有這個 HTML:
Assume you have this HTML:
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
請注意,層次結構是扁平的.
Note that the hierarchy is flat.
現在嘗試選擇 <p>
元素的中間對".這可能嗎?我實在想不通.
Now try to select the "middle pair" of <p>
elements. Is this possible? I really can't figure out how.
這個選擇器只抓取<h1>
之后的第一個<p>
:
This selector only grabs the first <p>
following the <h1>
:
h1:nth-of-type(2) + p
但是這個選擇器會抓取正確的一對 <p>
元素加上所有出現在后面的 <p>
元素我們想要的一對:
But this selector grabs the correct pair of <p>
elements plus all the following <p>
elements that appear after the pair we want:
h1:nth-of-type(2) ~ p
有可能嗎?
沒有 JavaScript.沒有標記更改.通用解決方案.允許任意數量的 <h1>
s 或 <p>
s,在這種情況下,數字 2 是任意的.
No JavaScript. No markup changing. Generic solution. Any number of <h1>
s or <p>
s are allowed, and the number two, in this case, is arbitrary.
我在想也許這可以使用一些使用 :not()
選擇器,但我似乎無法弄清楚.有點像選擇一般兄弟姐妹",然后根據需要排除,或類似的東西.
I'm thinking maybe this is possible using some using the :not()
selector, but I can't seem to figure it out. Kind of like selecting the "general siblings" and then excluding as necessary, or something similar.
推薦答案
由于一般同級組合器的工作方式,不可能將同級的選擇限制在特定范圍或組中,即使是連續的同級.甚至 :not()
選擇器在這里也沒有任何幫助.
Due to the way the general sibling combinator works, it is not possible to limit a selection of siblings to a specific range or group, even of consecutive siblings. Even the :not()
selector won't be of any help here.
您將必須使用 JavaScript 來定位正確的元素.jQuery 的 .nextUntil()
方法 立即浮現在腦海中.
You will have to use JavaScript to target the right elements. jQuery's .nextUntil()
method immediately springs to mind.
這篇關于如何定位平面層次結構中的特定兄弟姐妹組?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!