CSS:highlights 静态属性

Baseline 2025
Newly available

Since June 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

CSS 接口的静态只读属性 highlights 提供访问 HighlightRegistry 的能力,通过使用 CSS 自定义高亮 API 为任意文本范围添加样式。

示例

以下示例演示了如何创建多个文本范围,然后为它们创建 Highlight 对象,在 HighlightRegistry 中注册该高亮显示,最后使用 ::highlight() 伪元素为文本范围添加样式。

js
const parentNode = document.getElementById("foo");

const range1 = new Range();
range1.setStart(parentNode, 10);
range1.setEnd(parentNode, 20);

const range2 = new Range();
range2.setStart(parentNode, 40);
range2.setEnd(parentNode, 60);

const myCustomHighlight = new Highlight(range1, range2);

CSS.highlights.set("my-custom-highlight", myCustomHighlight);
css
::highlight(my-custom-highlight) {
  background-color: yellow;
  color: black;
}

规范

Specification
CSS Custom Highlight API Module Level 1
# dom-css-highlights

浏览器兼容性

参见