【1日1本の互換性】のIE 6、7のsetAttribute

11825 ワード

質問:
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>

このような問題のプロパティの要約:
  • class
  • for
  • cellspacing
  • cellpadding
  • tabindex
  • readonly
  • maxlength
  • rowspan
  • colspan
  • usemap
  • frameborder
  • contenteditable
  • 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');