首頁 >web前端 >css教學 >您可以使用純 CSS 根據錨點的內容設定錨點樣式嗎?

您可以使用純 CSS 根據錨點的內容設定錨點樣式嗎?

Susan Sarandon
Susan Sarandon原創
2024-11-15 07:46:021078瀏覽

Can You Style Anchors Based on Their Content Using Pure CSS?

Styling Anchors Based on Content Using CSS

Can you apply distinct styling to anchors containing a specific word using pure CSS? Though the proposal of the :contains selector was considered in the past, it's currently not part of the official CSS3 Selectors specification.

Solution:

Since pure CSS lacks the ability to target anchors based on their content, JavaScript becomes the alternative solution.

Array.from(document.links).forEach(link => {
  if (/\bSpecificWord\b/i.test(link.innerHTML)) {
    link.style.color = 'red';
  }
});

This script will iterate through all the links on a page and check if they contain the "SpecificWord" string anywhere within their HTML content. If a match is found, the link's color will be set to red, as specified in the style property.

Usage:

To use this solution, you can embed the script into an HTML page. Here's an example:

<a href="#">SpecificWord</a>
<a href="#">OtherWords</a>

<script>
  Array.from(document.links).forEach(link => {
    if (/\bSpecificWord\b/i.test(link.innerHTML)) {
      link.style.color = 'red';
    }
  });
</script>

This script will turn the first anchor element red, as it contains the "SpecificWord" string.

以上是您可以使用純 CSS 根據錨點的內容設定錨點樣式嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn