同樣是獲得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區別的理解。