如何在平面层次结构中定位特定组的同级? [英] How can I target a specific group of siblings in a flat hierarchy?

查看:84
本文介绍了如何在平面层次结构中定位特定组的同级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您拥有此HTML:

 < h1>标题1< / h1> 
< p> Lorem ipsum dolor sit amet,consectetur adipiscing elit。< / p>
< p> Lorem ipsum dolor sit amet,consectetur adipiscing elit。< / p>
< h1>标题1< / h1>
< p> Lorem ipsum dolor sit amet,consectetur adipiscing elit。< / p>
< p> Lorem ipsum dolor sit amet,consectetur adipiscing elit。< / p>
< h1>标题1< / h1>
< p> Lorem ipsum dolor sit amet,consectetur adipiscing elit。< / p>
< p> Lorem ipsum dolor sit amet,consectetur adipiscing elit。< / p>

请注意,层次结构是平的。



现在尝试选择< p> 元素的中间对。这可能吗?我真的不知道如何。



这个选择器只抓住第一个< p> code>< h1> :

  h1:但是这个选择器抓住了正确的<$ c(2)+ $ c>< p> 元素加上所有以下< p> 元素

  h1:nth-​​of-type(2)〜p 

有可能吗?



无标记更改。通用解决方案。允许任何数量的< h1> s或< p>



我想可能这是可能的使用一些使用:not() selector,但我似乎无法想象出来。

解决方案

由于通用的方式,兄弟姐妹组合器工作,不可能将兄弟姐妹的选择限制到特定范围或组,甚至连续的兄弟姐妹。即使:not()选择器也不会有任何帮助。



/ em>必须使用JavaScript来定位正确的元素。 jQuery的 .nextUntil()方法立即弹出。


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.

Now try to select the "middle pair" of <p> elements. Is this possible? I really can't figure out how.

This selector only grabs the first <p> following the <h1>:

h1:nth-of-type(2) + 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

Is it possible?

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.

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.

解决方案

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.

You will have to use JavaScript to target the right elements. jQuery's .nextUntil() method immediately springs to mind.

这篇关于如何在平面层次结构中定位特定组的同级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆