假设你有这个 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模板网!
每隔三个元素设置样式?Style every third element?(每隔三个元素设置样式?)
为什么我不应该在 CSS 中使用 ID 选择器?Why shouldn#39;t I use ID selectors in CSS?(为什么我不应该在 CSS 中使用 ID 选择器?)
CSS 中的 img[class*=“align"] 是什么意思?What does img[class*=quot;alignquot;] mean in CSS?(CSS 中的 img[class*=“align] 是什么意思?)
CSS:最后一个元素CSS: Last element on line(CSS:最后一个元素)
如何仅使用 CSS(无 js)选择所有其他 div 类元素How do I select every other div class element using just CSS (no js)(如何仅使用 CSS(无 js)选择所有其他 div 类元素)
检查未使用的 CSS 选择器的工具?Tool for checking unused CSS selectors?(检查未使用的 CSS 选择器的工具?)