运行 ❯
获取您
自己的
网站
×
更改方向
保存代码
更改主题,暗/亮
前往 Spaces
<html> <head> <style> #colorText { font-family: monospace; font-size: 25px; } ::highlight(mycolor-1) { color: red; } ::highlight(mycolor-2) { color: green; } ::highlight(mycolor-3) { color: blue; } ::highlight(mycolor-4) { color: salmon; } </style> </head> <body> <h1>Demo of ::highlight</h1> <p id="colorText">CSS Custom Highlight</p> <script> const textNode = document.getElementById("colorText").firstChild; if (!CSS.highlights) { textNode.textContent = "Highlight API is not supported!"; } // Create and register highlights for each color const highlights = []; for (let i = 0; i < 4; 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(`mycolor-${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 when reached the 4th. highlights[i % 4].add(range); } </script> </body> </html>