如设置class属性

el.setAttribute('class', 'abc');

在IE6/7中样式“abc”将没有起作用,虽然使用el.getAttribute('class')能取到值“abc”。

又如for属性

<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]), val);
		},
		
		getAttr : function(el, name) {
			return el.getAttribute(supportSetAttr ? name : fixAttr[name]);
		}
	}
})();

好了,现在不用考虑className/htmlFor了,都使用class/for即可。

dom.setAttr(el, 'class', 'red');
dom.getAttr(el, 'class');

相关:

IE6/7中使用setAttribute设置table的cellpadding和cellspacing的Bug

设置元素class的三种方式

作者: snandy 发表于 2011-08-27 10:26 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"