CSS 函式 - attr()



CSS 中的attr()函式用於檢索所選元素的屬性值,並在以後將其用於樣式表。attr()函式也可以用於偽元素,在這種情況下,該函式返回偽元素的源元素的屬性值。

attr()函式可以與任何 CSS 屬性一起使用,但對content屬性的支援是完整的,而對 type-or-unit 引數的支援並不全面。

可能的值

attr()函式可以採用以下值作為引數。

  • attribute-name 值:列出在 CSS 中引用的 HTML 元素上的屬性名稱。

語法

attr(<attribute-name>)

CSS attr() - 內容屬性

以下是一個 attr() 函式的示例。它將返回所選元素的屬性值,在本例中是錨元素 (a)。

<html>
<head>
<style>
   a:before {
      content: attr(href) " ** ";
   }
   
   a {
      text-decoration-line: underline;
      color: red;
   }
</style>
</head>
<body>
   <h2>The attr() Function</h2>
   <p>Insert ** before the anchor element</p>
   <a href="https://tutorialspoint.tw">
      Tutorialspoint
   </a>
</body>
</html>

以上示例在<a>元素的 href 屬性之前添加了兩個星號。它與 'content' 屬性以及偽元素 ::before 一起使用。

CSS attr() - 使用“title”屬性

以下是一個 attr() 函式的示例。它將返回縮寫的“title”屬性的值。

<html>
<head>
<style>
   abbr[title]:after {
      content: " (" attr(title) ")";
      background-color: aquamarine;
      font-size: 1.2rem;
   }
</style>
</head>
<body>
   <h2>"title" attribute of abbreviation</h2>
   <abbr title="Hyper Text Markup Language">
      HTML
    </abbr>
</body>
</html>

CSS attr() - 使用 @media 規則(列印頁面)

以下是一個 attr() 函式的示例,其中超連結顯示在頁面的列印版本中。這是使用 @media 規則完成的。請檢視示例

<html>
<head>
<style>
   @media print {
      a[href]:after {
         content: " (" attr(href) ")";
      }
   }
</style>
</head>
<body>
   <h2>hyperlink on print media</h2>
   <p>Press Ctrl+P to print the page and see the url of the link</p>
   <a href="www.tutorialspoint.com" target="_blank" rel="no-follow">Tutorials point</a>
</body>
</html>

CSS attr() - 使用自定義 HTML5 屬性

以下是一個 attr() 函式的示例,其中定義了一個自定義屬性 (sample-desc)。在列表中將某個值傳遞給此屬性。顯示相同的值,並且在未將值傳遞給自定義屬性的列表項中返回空白。讓我們看看示例

<html>
<head>
<style>
   li:after {
      content: " (" attr(sample-desc) ")";
      background-color: bisque;
   }
</style>
</head>
<body>
   <h2>custom data attribute of HTML5</h2>
   <ul>
      <li sample-desc="Cascading Style Sheets">
        CSS
      </li>
      <li sample-desc="Object-oriented Programming Language">
        JavaScript
      </li>
      <li>
        HTML
      </li>
      <li sample-desc="Web Browser">
        Chrome
      </li>
      <li sample-desc="Open-source JS Library">
        React
      </li>
    </ul>
</body>
</html>
廣告