比如設置 class:
el.setAttribute('class', 'abc');
在 IE6/7 中樣式 "abc" 完全不會生效——雖然你用 el.getAttribute('class') 又能取到值 "abc"。這才是最具迷惑性的地方:值明明寫進去了,瀏覽器卻不買賬。
再比如 label 的 for 屬性:
<label>姓名:</label><input type="checkbox" id="name"/>
<script>
var lab = document.getElementsByTagName('label')[0];
lab.setAttribute('for', 'name');
</script>
我們知道 label 一旦設了 for,點擊它就會自動選中對應的 checkbox。但上面這段代碼在 IE6/7 裡點擊 label 不會有任何反應。
類似問題還出現在 cellspacing / cellpadding 上。完整清單如下:
class for cellspacing cellpadding tabindex readonly maxlength rowspan colspan usemap frameborder contenteditable
仔細看的話會發現規律:這些屬性名要麼與 JS 關鍵字/保留字同名(class、for),要麼在 DOM 裡對應著另一個駝峰命名的 JS 屬性(tabIndex、readOnly、cellSpacing、rowSpan……)。IE6/7 的 DOM 實現正是在這裡出了偏差。
寫通用的 setAttribute / getAttribute 封裝時,需要把這些特殊性質考慮進去:
dom = (function() {
var fixAttr = {
tabindex: 'tabIndex',
readonly: 'readOnly',
'for': 'htmlFor',
'class': 'className',
maxlength: 'maxLength',
cellspacing: 'cellSpacing',
cellpadding: 'cellPadding',
rowspan: 'rowSpan',
colspan: 'colSpan',
usemap: 'useMap',
frameborder: 'frameBorder',
contenteditable: 'contentEditable'
},
div = document.createElement('div');
div.setAttribute('class', 't');
var supportSetAttr = div.className === 't';
return {
setAttr : function(el, name, val) {
el.setAttribute(supportSetAttr ? name : (fixAttr[name] || name), val);
},
getAttr : function(el, name) {
return el.getAttribute(supportSetAttr ? name : (fixAttr[name] || name));
}
}
})();
這段封裝的三層邏輯值得細看:
fixAttr[name] || name 的後半段)。而 supportSetAttr 這個判斷尤其巧妙:先用一個新建的 div 試著 setAttribute('class', 't'),再看 className 是否真的變成了 't'。與其去嗅探 userAgent 判斷版本號,不如直接問瀏覽器「你到底支不支援」——這才是特性檢測的正確姿態。
封裝之後,調用方再也不用糾結該寫 class 還是 className、for 還是 htmlFor:
dom.setAttr(el, 'class', 'red'); dom.getAttr(el, 'class'); dom.setAttr(el, 'for', 'userName'); dom.getAttr(el, 'for');
統一用 HTML 特性的原始寫法即可,兼容性細節全部收在封裝內部。