≪ Today I learned.
RSS購読
    公開日
    タグ
    JavaScript , CSS
    著者
    ダーシノ

    CSS Custom Highlight APIで任意のテキストをハイライトする

    CSS Custom Highlight APIを使うことで、JavaScriptで範囲を指定し、任意のスタイル(ハイライトなど)を適用できる。

    マウスで選択した部分のスタイルを変更する::selectionや、#:~:text=***のようにURLのハッシュを使って特定のテキストの選択してスタイルを変更する::target-textのような強調表示のぎ疑似要素を拡張して、任意の範囲をハイライトするためのAPIである。

    Highlight APIは、不要な要素を追加せずにCSSの疑似要素でスタイルを適用できるため、パフォーマンスやアクセシビリティの向上にもつながる。

    <p class="message">Hello world. This is a message to highlight.</p>
    const node = document.querySelector('.message').firstChild;
    
    const target = 'message'
    const start = node.textContent.indexOf(target);
    const end = start + target.length;
    
    // 1.Rangeオブジェクトを作成する
    const range = new Range()
    range.setStart(node, start)
    range.setEnd(node, end)
    
    // 2.Highlight APIを使ってハイライトする
    const highlight = new Highlight(range)
    CSS.highlights.set('selected', highlight)
    
    // 3. ハイライトを削除する
    // CSS.highlights.delete('highlight')
    // CSS.highlights.clear()
    ::highlight(selected) {
      background-color: #333;
      color: #fff;
    }

    デモ

    The CSS Highlight API allows developers to highlight specific parts of text on a web page without changing the HTML structure.

    By using JavaScript to create a Range and adding it to a Highlight object, you can define which words or phrases should be styled.

    Then, using the ::highlight() pseudo-element in CSS, you can set the background color or other styles.

    This API is useful for search results, grammar tools, and any feature that needs dynamic text highlighting.