谈谈JS中property和attribute的区别

property称为属性,而attribute称为特性!特殊的属性就叫特性!(如className,href等等)

property和attribute的区别

1)公认的attribute会映射到property

现在我们来看一个元素的全部属性(用console.dir即可得到)

谈谈JS中property和attribute的区别

里面的attributes就是特性,特性就是该元素所特有的属性,其他的都是property,所有元素都有的特性就会被映射会属性!!

 

2)读写方式不一样

property:  读:element.property;                            如:p.className;

                写:element.property = 'xxx';                如:p.className = 'xiao';

attribute:   读:element.getAttribute('属性名','属性值');  如:element.getAttribute('href');

                写:element.setAttribute('属性名','属性值');  如:element.getAttribute('href','xiaowan.jpg');

 

3)特别的值,如class,style等

class

property:   要获得class属性,需要改为className,因为class是关键字  即使用方式为:element.className;

attribute:   不需要修改,用常规的getAttribute和setAttribute方法即可

 

style

property:  element.style是一个对象,而不是一个属性,该对象中包含了很多属性,如果我们访问字体颜色则用:

                 element.style.color;如果属性为多个字符连接而成,则用驼峰表示法:如element.style.backgroundColor;

 

attribute:如果我们想修改字体颜色或访问,直接用color或者访问color即可,如 element.setAttribute('color', 'red');

 

本博客属于作者原创,如需转载请注明出处!!!