::highlight()

Limited availability

此功能不是基线,因为它在一些最常用的浏览器中不起作用。

::highlight() CSS 伪元素 将样式应用于自定义高亮显示。

自定义高亮显示是一组 Range 对象,并使用 HighlightRegistry 在网页上注册。

允许的属性

只有某些 CSS 属性可以与 ::highlight() 一起使用

特别是,background-image 被忽略。

语法

css
::highlight(custom-highlight-name)

示例

突出显示字符

HTML

html
<p id="rainbow-text">CSS Custom Highlight API rainbow</p>

CSS

css
#rainbow-text {
  font-family: monospace;
  font-size: 1.5rem;
}

::highlight(rainbow-color-1) {
  color: #ad26ad;
  text-decoration: underline;
}
::highlight(rainbow-color-2) {
  color: #5d0a99;
  text-decoration: underline;
}
::highlight(rainbow-color-3) {
  color: #0000ff;
  text-decoration: underline;
}
::highlight(rainbow-color-4) {
  color: #07c607;
  text-decoration: underline;
}
::highlight(rainbow-color-5) {
  color: #b3b308;
  text-decoration: underline;
}
::highlight(rainbow-color-6) {
  color: #ffa500;
  text-decoration: underline;
}
::highlight(rainbow-color-7) {
  color: #ff0000;
  text-decoration: underline;
}

JavaScript

js
const textNode = document.getElementById("rainbow-text").firstChild;

if (!CSS.highlights) {
  textNode.textContent =
    "The CSS Custom Highlight API is not supported in this browser!";
}

// Create and register highlights for each color in the rainbow.
const highlights = [];
for (let i = 0; i < 7; i++) {
  // Create a new highlight for this color.
  const colorHighlight = new Highlight();
  highlights.push(colorHighlight);

  // Register this highlight under a custom name.
  CSS.highlights.set(`rainbow-color-${i + 1}`, colorHighlight);
}

// Iterate over the text, character by character.
for (let i = 0; i < textNode.textContent.length; i++) {
  // Create a new range just for this character.
  const range = new Range();
  range.setStart(textNode, i);
  range.setEnd(textNode, i + 1);

  // Add the range to the next available highlight,
  // looping back to the first one once we've reached the 7th.
  highlights[i % 7].add(range);
}

结果

规范

规范
CSS Custom Highlight API Module Level 1
# custom-highlight-pseudo

浏览器兼容性

BCD 表格仅在浏览器中加载