<p id="rainbow-text">CSS Custom Highlight API</p>
html,
body {
margin: 0;
width: 100%;
height: 100%;
display: flex;
background: aliceblue;
align-items: center;
justify-content: center;
}
#rainbow-text {
font-family: monospace;
font-size: 3rem;
}
::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;
}
const textNode = document.getElementById("rainbow-text").firstChild;
if (CSS.highlights) {
const highlights = [];
for (let i = 0; i < 7; i++) {
// 给每个颜色实例化一个Highlight对象
const colorHighlight = new Highlight();
highlights.push(colorHighlight);
// 注册高亮
CSS.highlights.set(`rainbow-color-${i + 1}`, colorHighlight);
}
// 遍历文本节点
for (let i = 0; i < textNode.textContent.length; i++) {
// 给每个字符创建一个选区
const range = new Range();
range.setStart(textNode, i);
range.setEnd(textNode, i + 1);
// 添加到高亮
highlights[i % 7].add(range);
}
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.