::highlight()
::highlight() CSS 伪元素用于为自定义高亮应用样式。
自定义高亮是 Range 对象的集合,并通过 HighlightRegistry 在网页上注册。
::highlight() 伪元素遵循所有高亮伪元素共有的特殊继承模型。有关此继承如何工作的更多详细信息,请参阅高亮伪元素继承部分。
允许的属性
只有某些 CSS 属性可以与 ::highlight() 一起使用:
colorbackground-colortext-decoration及其相关属性text-shadow-webkit-text-stroke-color、-webkit-text-fill-color和-webkit-text-stroke-width
特别是,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: violet;
text-decoration: underline;
}
::highlight(rainbow-color-2) {
color: purple;
text-decoration: underline;
}
::highlight(rainbow-color-3) {
color: blue;
text-decoration: underline;
}
::highlight(rainbow-color-4) {
color: green;
text-decoration: underline;
}
::highlight(rainbow-color-5) {
color: yellow;
text-decoration: underline;
}
::highlight(rainbow-color-6) {
color: orange;
text-decoration: underline;
}
::highlight(rainbow-color-7) {
color: red;
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 自定义高亮 API 模块级别 1 # custom-highlight-pseudo |
| CSS 伪元素模块 Level 4 # selectordef-highlight-custom-ident |
浏览器兼容性
加载中…
另见
- CSS 自定义高亮 API 模块
- CSS 自定义高亮 API
- CSS 伪元素模块