| 如设置class属性 复制代码<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'); 
 |