::highlight()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Phần tử giả ::highlight() trong CSS áp dụng các kiểu cho một highlight tùy chỉnh.
Một highlight tùy chỉnh là tập hợp các đối tượng Range và được đăng ký trên một trang web bằng cách sử dụng HighlightRegistry.
Phần tử giả ::highlight() tuân theo mô hình kế thừa đặc biệt chung cho tất cả các phần tử giả highlight. Để biết thêm chi tiết về cách kế thừa này hoạt động, xem phần Kế thừa của các phần tử giả highlight.
Các thuộc tính được phép sử dụng
Chỉ một số thuộc tính CSS nhất định có thể được dùng với ::highlight():
colorbackground-colortext-decorationvà các thuộc tính liên quantext-shadow-webkit-text-stroke-color,-webkit-text-fill-colorvà-webkit-text-stroke-width
Đặc biệt, background-image bị bỏ qua.
Cú pháp
css
::highlight(custom-highlight-name)
Ví dụ
>Làm nổi bật các ký tự
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);
}
Kết quả
Thông số kỹ thuật
| Specification |
|---|
| CSS Custom Highlight API Module Level 1> # custom-highlight-pseudo> |
| CSS Pseudo-Elements Module Level 4> # selectordef-highlight-custom-ident> |
Tương thích trình duyệt
Xem thêm
- Module CSS custom highlight API
- API CSS custom highlight
- Module CSS pseudo-elements