Heim  >  Artikel  >  Web-Frontend  >  HTML5 data-* 自定义属性_html/css_WEB-ITnose

HTML5 data-* 自定义属性_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:42:09836Durchsuche

在jQuery的attr与prop提到过在IE9之前版本中如果使用property不当会造成内存泄露问题,而且关于Attribute和Property的区别也让人十分头痛,在HTML5中添加了data-*的方式来自定义属性,所谓data-*实际上上就是data-前缀加上自定义的属性名,使用这样的结构可以进行数据存放。使用data-*可以解决自定义属性混乱无管理的现状。

读写方式

data-*有两种设置方式,可以直接在HTML元素标签上书写

<div id="test" data-age="24">        Click Here    </div>

其中的data-age就是一种自定义属性,当然我们也可以通过JavaScript来对其进行操作,HTML5中元素都会有一个dataset的属性,这是一个DOMStringMap类型的键值对集合

var test = document.getElementById('test');        test.dataset.my = 'Byron';

这样就为div添加了一个data-my的自定义属性,使用JavaScript操作dataset有两个需要注意的地方

1. 我们在添加或读取属性的时候需要去掉前缀data-*,像上面的例子我们没有使用test.dataset.data-my = 'Byron';的形式。

2. 如果属性名称中还包含连字符(-),需要转成驼峰命名方式,但如果在CSS中使用选择器,我们需要使用连字符格式

为刚才代码追加写内容

<style type="text/css">        [data-birth-date]        {            background-color: #0f0;            width:100px;            margin:20px;        }    </style>

test.dataset.birthDate = '19890615';

这样我们通过JavaScript设置了data-birth-date自定义属性,在CSS样式表为div添加了一些样式,看看效果

读取的时候也是通过dataset对象,使用”.”来获取属性,同样需要去掉data-前缀,连字符需要转化为驼峰命名

var test = document.getElementById('test');        test.dataset.my = 'Byron';        test.dataset.birthDate = '19890615';        test.onclick = function () {            alert(this.dataset.my + ' ' + this.dataset.age+' '+this.dataset.birthDate);        }

getAttribute/setAttribute

有些同学可能会问这和getAttribute/setAttribute除了命名有什么区别吗,我们来看一下

var test = document.getElementById('test');        test.dataset.birthDate = '19890615';        test.setAttribute('age', 25);        test.setAttribute('data-sex', 'male');        console.log(test.getAttribute('data-age')); //24        console.log(test.getAttribute('data-birth-date')); //19890516        console.log(test.dataset.age); //24        console.log(test.dataset.sex); //male

这样我们可以看出,两者都把属性设置到了attribute上(废话,要不人家能叫自定义属性),也就是说getAttribute/setAttribute可以操作所有的dataset内容,dataset内容只是attribute的一个子集,特殊就特殊在命名上了,但是dataset内只有带有data-前缀的属性(没有age=25那个)。

那么为什么我们还要用data-*呢,一个最大的好处是我们可以把所有自定义属性在dataset对象中统一管理,遍历啊神马的都哦很方便,而不至于零零散散了,所以用用还是不错的。

浏览器兼容性

比较不好的消息就是data-*的浏览器兼容性情况十分不乐观

  • Internet Explorer 11+
  • Chrome 8+
  • Firefox 6.0+
  • Opera 11.10+
  • Safari 6+
  • 其中IE11+简直就是亮瞎小伙伴的眼,看来要想全面使用此属性路漫漫其修远矣

    此文转自:http://www.cnblogs.com/dolphinX/p/3348458.html

    Stellungnahme:
    Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn