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

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

Susan Sarandon
發布: 2024-11-15 07:46:02
原創
1023 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板