HTML data-* 属性是全局属性,用于形成一类属性,这些属性定义了我们自己的自定义数据属性,并将自定义数据存储在页面或应用程序上。
以下是此数据属性的各个部分
- Attribute Name:它包含一个字符长,不包含大写字母,并以“data-*”为前缀。
- Attribute Value:可以是任何字符串。
语法
<element data-* = "10784"> ...内容 </element >
在这里,“*”可以是任何东西,如您将在以下示例中看到的那样。
适用于
大多数 HTML 元素都支持 data-* 属性,但也有一些例外。通常不用于包含内容的元素,或者在自定义数据属性适用的情况下没有任何内部功能的元素可能不支持它们。例如<style>、<html>、<title>、<script>、<meta>几个不支持自定义数据属性的标签。
HTML data-* 属性的示例
下面的示例将说明 HTML data-* 属性,我们应该在哪里以及如何使用此属性!
使用 data-* 属性定义自定义数据
在以下示例中,我们将创建一个 itema 列表并定义每个项目的 data-course-type。
<!DOCTYPE html>
<html>
<head>
<title>HTML data-* Attribute</title>
</head>
<body>
<ul>
<li data-course-type="frontEnd">HTML</li>
<li data-course-type="backEnd">Php</li>
<li data-course-type="fullStack">MERN</li>
</ul>
</body>
<html>
在悬停上显示自定义数据
在以下示例中,我们将创建一个 HTML 文档并使用 data-* 属性来嵌入自定义数据,如下所示:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
margin: 0;
}
ul {
margin: 10px 0 0;
}
li {
position: relative;
width: 200px;
padding-bottom: 10px;
}
li:after {
content: 'Data ID: 'attr(data-id);
position: absolute;
top: -22px;
left: 10px;
background: black;
color: white;
padding: 2px;
border: 1px solid #eee;
opacity: 0;
transition: 0.5s opacity;
}
li:hover:after {
opacity: 1;
}
</style>
</head>
<body>
<h1>Secret agents</h1>
<ul>
<li data-id="10784">
Jason Walters, 003: Found dead in "A View to a Kill".
</li>
<li data-id="97865">
Alex Trevelyan, 006: Agent turned terrorist leader.
</li>
<li data-id="45732">
James Bond, 007: The main man; shaken but not stirred.
</li>
</ul>
</body>
</html>
在 JavaScript 中使用自定义数据
让我们看一下另一个示例,我们将使用 data-* 属性来嵌入自定义数据。这里的 data-org-type 将存储当前 li 元素中的组织类型。
<!DOCTYPE html>
<html>
<head>
<title>data-* attribute</title>
</head>
<body>
<h1>Organizations</h1>
<p>Click on a organization to see what type it is:</p>
<ul>
<li onclick="showDetails(this)"
id="qikepucom"
data-org-type="EdTech organization">
qikepucom
</li>
<li onclick="showDetails(this)"
id="amazon"
data-org-type="E-commerce organization">
Amazon
</li>
<li onclick="showDetails(this)"
id="google"
data-org-type="It & Product Based organization">
Google
</li>
<p id="type"></p>
</ul>
<script>
function showDetails(org) {
let orgType = org.getAttribute("data-org-type");
document.getElementById("type").innerHTML =
("The " + org.innerHTML + " is a " + orgType + ".");
}
</script>
</body>
</html>
支持浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | 4.0 | 5.5 | 2.0 | 3.1 | 9.6 |