IE6/7中setAttribute不支持class/for/rowspan/colspan等属性

今天在学习中遇到了在ie中设置class属性值的bug,现写出来与大家分享,一起共勉,如有错漏望不吝指正。


如:


elm.setAttribute('class', 'className');

在IE6/7中样式“className”并没有起作用,虽然使用elm.getAttribute('class')是可以获取到“className”。

后来上网查了一些资料,发现了在ie中其实还有一部分属性也会有这样的问题,像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');

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章