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

今天在学习中遇到了在ie中设置class属性值的bug,现写出来与你们分享,一块儿共勉,若有错漏望不吝指正。html


如:浏览器


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

在IE6/7中样式“className”并无起做用,虽然使用elm.getAttribute('class')是能够获取到“className”。dom

后来上网查了一些资料,发现了在ie中其实还有一部分属性也会有这样的问题,像for属性ide





 
<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。post

 

并且相似的状况还发生在 cellspacing/cellpadding 等属性上,现列出来,你们能够认一下,之后作的时候能够注意一下:学习

classspa

forhtm

cellspacingblog

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');
相关文章
相关标签/搜索