IE6、IE7中setAttribute不支援class/for/rowspan/colspan等屬性

來源:互聯網
上載者:User

如設定class屬性
複製代碼 代碼如下:el.setAttribute('class', 'abc');
在IE6/7中樣式“abc”將沒有起作用,雖然使用el.getAttribute('class')能取到值“abc”。

又如for屬性
複製代碼 代碼如下:
<label>姓名:</label><input type="checkbox" id="name"/>
<script>
var lab = document.getElementsByTagName('label')[0];
lab.setAttribute('for', 'name');
</script>

我們知道當lab設定了for屬性,點擊label將自動將對應的checkbox選中。但以上設定在IE6/7點擊將不會選中checkbox。

類似的情況還發生在 cellspacing/cellpadding 上。匯總如下:
class
for
cellspacing
cellpadding
tabindex
readonly
maxlength
rowspan
colspan
usemap
frameborder
contenteditable
因此,當寫一個通用的跨瀏覽器的設定元素屬性的介面方法時需要考慮注意以上屬性在IE6/7中的特殊性。如下
複製代碼 代碼如下:
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));
}
}
})();

首先,標準瀏覽器直接使用原始屬性名稱;其次,IE6/7非以上列舉的屬性仍然用原始屬性名稱;最後這些特殊屬性(與JS關鍵字同名如for,class)使用fixAttr。
好了,現在不用考慮className/htmlFor了,都使用class/for即可。
複製代碼 代碼如下:
dom.setAttr(el, 'class', 'red');
dom.getAttr(el, 'class');
dom.setAttr(el, 'for', 'userName');
dom.getAttr(el, 'for');

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.