【一天一道兼容性】之——IE6、7中的setAttribute

问题

demo1

1 elem.setAttribute('class', 'bg');  //IE6、7中无效果

demo2

<label>姓名:</label><input type="checkbox" id="name"/>
<script>
    var lab = document.getElementsByTagName('label')[0];
    lab.setAttribute('for', 'name');   //IE6、7点击将不会选中checkbox     
</script>

demo3:

<p id="p1" style="color: red">字体颜色</p>
<script>
     var p = document.getElementById("p1");
     alert(p.getAttribute("style"));           //IE6、7:object   
     p.setAttribute("style", "color:blue");    //IE6、7:无效果  
</script>

此类问题属性汇总:

  1. class
  2. for
  3. cellspacing
  4. cellpadding
  5. tabindex
  6. readonly
  7. maxlength
  8. rowspan
  9. colspan
  10. usemap
  11. frameborder
  12. contenteditable
  13. style

解决方案:

 1 var dom = (function () {
 2             var fixAttr = {
 3                 "class": "className",
 4                 "for": "htmlFor",
 5                 "cellspacing": "cellSpacing",
 6                 "cellpadding": "cellPadding",
 7                 "tabindex": "tabIndex",
 8                 "readonly": "readOnly",
 9                 "maxlength": "maxLength",
10                 "rowspan": "rowSpan",
11                 "colspan": "colSpan",
12                 "usemap": "useMap",
13                 "frameborder": "frameBorder",
14                 "contenteditable": "contentEditable"
15             },
16             supportSetAttr,
17             div = document.createElement("div");
18             div.setAttribute("class", "a");
19             supportSetAttr = div.className === 'a';
20             return {
21                 setAttr: function (elem, name, val) {
22                     if (name != "style")
23                         elem.setAttribute(supportSetAttr ? name : (fixAttr[name] || name), val);
24                     else
25                         elem.style.cssText = val;
26                 },
27                 getAttr: function (elem, name) {
28                     if (name != "style")
29                         return elem.getAttribute(supportSetAttr ? name : (fixAttr[name] || name));
30                     return elem.style.cssText.toLowerCase();
31                 }
32             }
33         }());

现在利用dom解决问题:

1 dom.setAttr(elem, 'class', 'bg');
2 dom.getAttr(elem, 'class');
3 
4 dom.setAttr(elem, 'style', 'color:blue');
5 dom.getAttr(elem, 'style');

 

posted on 2013-04-13 20:42  _xiaoMo_  阅读(460)  评论(1编辑  收藏  举报

导航