【一天一道兼容性】之——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>
此类问题属性汇总:
- 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');