CSS 中的 attr() 函数用于检索所选元素的属性值,然后将其用于样式表。函数 attr() 也可以用于伪元素,其中该函数返回伪元素的原始元素的属性值。
attr() 函数可以与任何 CSS 属性一起使用,但对 content 属性的支持是完整的,而对 type-or-unit 参数的支持并不彻底。
可能的值
函数 attr() 可以将以下值作为参数。
- attribute-name value:列出 CSS 中引用的 HTML 元素上的属性名称。
语法
attr(<attribute-name>)
CSS attr() - Content 属性
以下是 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://www.qikepu.com">
QikepuCom
</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.qikepu.com" target="_blank" rel="no-follow">Qikepu.Com</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>