:has() - CSS: Cascading Style Sheets 编辑

The :has() CSS pseudo-class represents an element if any of the selectors passed as parameters (relative to the :scope of the given element) match at least one element.

/* Selects any <a>, as long as it has an <img> element directly inside it  */
/* Note that this is not supported in any browser yet */
let test = document.querySelector('a:has(> img)');

Syntax

:has( <relative-selector-list> )

where
<relative-selector-list> = <relative-selector>#

where
<relative-selector> = <combinator>? <complex-selector>

where
<combinator> = '>' | '+' | '~' | [ '||' ]
<complex-selector> = <compound-selector> [ <combinator>? <compound-selector> ]*

where
<compound-selector> = [ <type-selector>? <subclass-selector>* [ <pseudo-element-selector> <pseudo-class-selector>* ]* ]!

where
<type-selector> = <wq-name> | <ns-prefix>? '*'
<subclass-selector> = <id-selector> | <class-selector> | <attribute-selector> | <pseudo-class-selector>
<pseudo-element-selector> = ':' <pseudo-class-selector>
<pseudo-class-selector> = ':' <ident-token> | ':' <function-token> <any-value> ')'

where
<wq-name> = <ns-prefix>? <ident-token>
<ns-prefix> = [ <ident-token> | '*' ]? |
<id-selector> = <hash-token>
<class-selector> = '.' <ident-token>
<attribute-selector> = '[' <wq-name> ']' | '[' <wq-name> <attr-matcher> [ <string-token> | <ident-token> ] <attr-modifier>? ']'

where
<attr-matcher> = [ '~' | | | '^' | '$' | '*' ]? '='
<attr-modifier> = i | s

Description

The :has() pseudo-class takes a relative selector list as an argument. In earlier revisions of the CSS Selectors Level 4 specification, :has had a limitation that it couldn't be used within stylesheets. Instead, it could only be used with functions like document.querySelector(); this was due to performance concerns. This limitation has been removed because no browser implemented it that way. Instead, browsers currently only support the use of :has() within stylesheets.

Examples

Matching <a> elements that directly contain an <img>

The following selector matches only <a> elements that directly contain an <img> child:

a:has(> img)

Matching <h1> elements that are followed by a <p>

The following selector matches <h1> elements only if they have a <p> element directly following them:

h1:has(+ p)

Specifications

SpecificationStatusComment
Selectors Level 4
The definition of ':has()' in that specification.
Working DraftInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:92 次

字数:14704

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文