data属性(The Data Attribute)

时间:2023-03-09 01:20:59
data属性(The Data Attribute)

HTML片段

<div id="myDiv" data-custom-attr="My Value"> 巴拉巴拉,lady 嘎嘎 </div>

检索自定义属性的价值

var theDiv = document.getElementById('myDiv');
var attr = theDiv.getAttribute('data-custom-attr');
alert(attr); // My Value

此属性还可以用在CSS中,例如下面这个有些傻里傻气的CSS文字改变的例子:

CSS代码:
.data_custom { display:inline-block; position: relative; }
.data_custom:hover { color: transparent; }
.data_custom:hover:after {
content: attr(data-hover-response);
color: black;
position: absolute;
left: 0;
}
HTML代码: <a class="data_custom" data-hover-response="我说过不要碰我!" href="#">不要碰我,雅蠛蝶~~</a>