视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
HTML中的attribute和property_html/css
2020-11-27 16:08:59 责编:小采
文档

一、概述

attribute和property是常常被弄混的两个概念。

简单来说,property则是JS代码里访问的:

document.getElementByTagName('my-element').prop1 = 'hello';

attribute类似这种:

JS代码里访问attribute的方式是getAttribute和setAttribute:

document.getElementByTagName('my-element').setAttribute('attr1','Hello');

document.getElementByTagName('my-element').getAttribute('attr1','Hello');

二、区别

多数情况下,两者是等效的。在web标准中,常常会规定某attribute“反射”了同名的property。但是例外的情况还是不少的。

1. 名字不一致

最典型的是className,为了回避JavaScript保留字,JS中跟class attribute对应的property是className。

//若value属性已经设置,则attribute不变,property变化,元素上实际的效果是property优先

input.value //hello

input.getAttribute('value'); //cute

除此之外,checkbox的显示状态由checked和indeterminate两个property决定,而只有一个名为checked的property,这种情况下property是更完善的访问模型。

三、特殊场景

1.mutation

使用mutation observer,只能监测到attribute变化。

var observer = new MutationObserver(function(mutations){

for(var i = 0; i < mutations.length; i++) {

var mutation = mutations[i];

console.log(mutation.attributeName);

}

});

observer.observe(element,{attributes:true});

element.prop1 = 'aa' // 不会触发

element.setAttribute('attr1', 'aa') //会触发

2.custom element

在使用WebComponents时,可以定义attribute和property,两者可以互相反射,也可以全无关联。

var MyElementProto = Object.create(HTMLElement.prototype, {

createdCallback : {

value : function() { }

}

});

//定义property

Object.defineProperty(MyElementProto,'prop1', {

get:function(){

return //

},

set:function(){

console.log('property change');//do something

}

});

//定义attribute

MyElementProto.attributeChangedCallback = function(attr, oldVal, newVal) {

if(attr === 'attr1') {

console.log('attribute change');//do something

}

};

window.MyElement = document.registerElement('my-element', {

prototype: MyElementProto

});

下载本文
显示全文
专题