是否有“包罗万象的兄弟姐妹"之类的东西?CSS 选择器?

编程入门 行业动态 更新时间:2024-10-09 23:12:22
本文介绍了是否有“包罗万象的兄弟姐妹"之类的东西?CSS 选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的 HTML:

<p>Doggies</p> <p class="green_guys">Froggies</p> <p>Cupcakes</p> <p>Piggies</p>

当用于选择 green_guys 的兄弟姐妹时,一个全包的兄弟姐妹选择器(如我所愿)将选择小狗纸杯蛋糕和小猪.

An all inclusive sibling selector (as I wish it to be), when used to select green_guys' siblings, would select the doggies cupcakes and piggies.

其他选择器:

+ 选择器(又名相邻兄弟选择器)只会选择纸杯蛋糕:

The + selector (a.k.a. adjacent sibling selector) would only select the cupcakes:

.green_guys + p { /* selects the <p> element that immediately follows .green_guys */ }

~ 选择器(又名通用兄弟选择器)只会选择纸杯蛋糕和小猪:

The ~ selector (a.k.a. general sibling selector) would only select the cupcakes, and piggies:

.green_guys ~ p { /* selects all <p> elements that follow .green_guys */ }

推荐答案

没有向后或向后看的兄弟组合子,只有向前看的相邻和一般兄弟组合子.

There is no sibling combinator that looks backward or around, only the adjacent and general sibling combinators that look forward.

您可以做的最好的事情是确定一种方法,将选择限制为仅具有相同父级的这些 p 元素,然后选择 p 子级 :not(.green_guys).例如,如果父元素的 ID 为 #parent,则可以使用此选择器:

The best you can do is determine a way to limit selection only to these p elements with the same parent, and then select the p children that are :not(.green_guys). If the parent element has an ID of #parent, for example, you can use this selector:

#parent > p:not(.green_guys) { /* selects all <p> children of #parent that are not .green_guys */ }

但是,即使 none 元素具有类,上述内容仍将匹配您的 p 元素.目前不可能仅在给定元素 存在 的情况下选择该元素的兄弟姐妹(这是兄弟组合器的目的 - 建立 两个 兄弟之间的关系元素).

However the above will still match your p elements even if none of them have the class. It is currently not possible to select the siblings of an element only given the existence of said element (which is the purpose of a sibling combinator — to establish a relationship between two sibling elements).

选择器 4 的 :has()有望在不需要前置兄弟组合器的情况下纠正此问题,从而产生以下解决方案:

Selectors 4's :has() will hopefully rectify this without the need for a preceding-sibling combinator, resulting in the following solution:

p:has(~ .green_guys), .green_guys ~ p { /* selects all <p> elements that are siblings of .green_guys */ }

如果父元素的所有子元素都没有该类,这将不匹配任何内容.

This will not match anything if none of the children of the parent element have the class.

更多推荐

是否有“包罗万象的兄弟姐妹"之类的东西?CSS 选择器?

本文发布于:2023-11-28 08:48:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641731.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:包罗万象   兄弟姐妹   东西   选择器   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!