同样是获得element的style属性,有两种方式el.style
和el.getAttribute('style')
。前者我们叫style
是el
的property,后者我们叫style
是el
的attribute。
参考attibute vs property和stack overflow上关于$.prop与$.attr的回答,我们可以总结为以下:
- DOM element是一个object,它具有的属性叫做property,property的类型有很多种,可以是string,number,obejct,function。
但是getAttribute(attrName)的返回值始终是string类型。 - DOM element通过getAttribute方法得到某属性的值,这个值的起源是html文本上的定义值。
对于简书的编辑栏,html文本是这样定义的
<textarea class="text mousetrap" name="note_content" style="height: 573px;">
</textarea>
浏览器根据这个文本生成dom element,发现这个定义里包含三个属性,分别是class
,name
,style
。我们在chrome dev tool里面查看这三个属性:
$0.getAttribute('class') // "text mousetrap"
$0.getAttribute('name') // "note_content"
$0.getAttribute('style') // "height: 573px;"
而直接通过el.propName或者el[propName],我们得到的是el作为dom element的属性,大部分prop与attr名称相同,但是有些不同,比如class与className
$0.className // "text mousetrap"
$0.classList // ['text', 'mousetrap'] ps: classList不是array类型
$0.name // "note_content"
$0.style
/* **
CSSStyleDeclaration {
0: "height",
alignContent: "",
alignItems: "",
alignSelf: "",
...
}
** */
查看style的值,我们可以发现其中的差别。
- 在实际应用中,大部分时候我们只需关注property,比如class,id,name,checked等等。它们通常代表有意义的web api。我们都知道class的语义,不管这个意义怎么表示。再看前面的element,它具有两个类名
text
和mousetrap
,那么无论是通过el.className = 'text mousetrap foo'
,或者el.classList.add('foo')
,还是el.setAttribute('class', 'text mousetrap foo')
,最终我们都成功地添加了新类名foo
,并且这种结果与el.className
和el.getAttribute('class')
是一致的。 - 当我们需要一些自定义的属性时,那么我们应该用attribute。最常见的就是定义在html文本里的
data-*
属性。
最后查看sprint.js对于prop与attr的实现,我们可以加深对prop与attr区别的理解。
网友评论