Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. CSS:层叠样式表
  3. CSS 参考
  4. 选择器
  5. :scope

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

:scope

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2020年1月.

:scopeCSS伪类表示作为选择器要匹配的作为参考点或作用域的元素。

css
/* 选择一个限制作用域的元素 */:scope {  background-color: lime;}

:scope 匹配的元素取决于它的使用上下文:

  • 当在样式表的根级别使用时,:scope 等效于:root——在常规 HTML 文档中匹配<html> 元素。
  • 当在@scope 块中使用时,:scope 匹配块所定义的作用域的根。它提供了一种从@scope 块内部应用样式到作用域的根的方法。
  • 当在 DOM API 调用(例如querySelector()querySelectorAll()matches()Element.closest())中使用时,:scope 匹配调用此类方法的元素。

语法

css
:scope {  /* ... */}

示例

使用:scope 来代替:root

此示例展示了当在样式表的根级别使用时,:scope 等效于:root。在当前示例中,提供的 CSS 会将<html> 元素的背景颜色设置为橙色。

HTML

html
<html></html>

CSS

css
:scope {  background-color: orange;}

结果

使用:scope 来为@scope 块的作用域的根元素设置样式

在此示例中,我们使用两个单独的@scope 块来匹配.light-scheme.dark-scheme 类中的链接。请注意,:scope 用于选择作用域的根元素并为其设置样式。在此示例中,作用域的根是应用了这些类的<div> 元素。

HTML

html
<div>  <p>    MDN 涵盖了很多有关    <a href="/zh-CN/docs/Web/HTML">HTML</a>、<a href="/zh-CN/docs/Web/CSS"      >CSS</a    >    和    <a href="/zh-CN/docs/Web/JavaScript">JavaScript</a> 的信息。  </p></div><div>  <p>    MDN 涵盖了很多有关    <a href="/zh-CN/docs/Web/HTML">HTML</a>、<a href="/zh-CN/docs/Web/CSS"      >CSS</a    >    和    <a href="/zh-CN/docs/Web/JavaScript">JavaScript</a> 的信息。  </p></div>

CSS

div {  padding: 10px;}
css
@scope (.light-scheme) {  :scope {    background-color: plum;  }  a {    color: darkmagenta;  }}@scope (.dark-scheme) {  :scope {    background-color: darkmagenta;    color: antiquewhite;  }  a {    color: plum;  }}

结果

在 JavaScript 中使用:scope

此示例演示了如何在 JavaScript 中使用:scope 伪类。如果你需要获取已获取的Element 的直接后代,这可能会很有用。

HTML

html
<div>  <div>    <div></div>    <div></div>  </div>  <div>    <div></div>  </div></div><p>选择的元素 id:<span></span></p>

JavaScript

js
const context = document.getElementById("context");const selected = context.querySelectorAll(":scope > div");document.getElementById("results").innerHTML = Array.prototype.map  .call(selected, (element) => `#${element.getAttribute("id")}`)  .join("、");

结果

context 的作用域是idcontext 的元素。所选元素是此上下文的直接子元素——element-1element-2——但不包括它们的后代。

规范

Specification
Selectors Level 4
# the-scope-pseudo

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp