列举所有的方式,看看各浏览器的支持差异。

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

<!DOCTYPE HTML>
<HTML>
 <HEAD>
	<meta charset="utf-8" />
	<title>setAttribute('class', 'abc')</title>
	<style type="text/css">
		.abc {
			background: red;
		}
	</style>
 </HEAD>
 <BODY>
 	<div >test div</div>
	<script>
		var div = document.getElementById('d1');
		div.setAttribute("class", "abc");
	</script>
 </BODY>
</HTML>

IE6/7 : div背景色不是红色

IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色为红色

结果:IE6/7不支持setAttribute('class',xxx)方式设置元素的class。

二、el.setAttribute('className', 'abc')

<!DOCTYPE HTML>
<HTML>
 <HEAD>
	<meta charset="utf-8" />
	<title>setAttribute('className', 'abc')</title>
	<style type="text/css">
		.abc {
			background: red;
		}
	</style>
 </HEAD>
 <BODY>
 	<div >test div</div>
	<script>
		var div = document.getElementById('d1');
		div.setAttribute("className", "abc");
	</script>
 </BODY>
</HTML> 

IE6/7 : div背景色为红色

IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色不是红色

结果:IE8/9/10/Firefox/Safari/Chrome/Opera不支持setAttribute('className',xxx)方式设置元素的class。

很有趣,使用setAttribute的时候第一个参数为class和className的情形在IE6/7和IE8/9/10/Firefox/Safari/Chrome/Opera刚好相反。

三、el.className = 'abc';

<!DOCTYPE HTML>
<HTML>
 <HEAD>
	<meta charset="utf-8" />
	<title>el.className = 'abc'</title>
	<style type="text/css">
		.abc {
			background: red;
		}
	</style>
 </HEAD>
 <BODY>
 	<div >test div</div>
	<script>
		var div = document.getElementById('d1');
		div.className = 'abc';
	</script>
 </BODY>
</HTML>

所有浏览器都支持。

相关文章:

  • 2021-11-19
  • 2021-07-30
  • 2022-12-23
  • 2021-12-20
  • 2022-12-23
  • 2022-02-16
  • 2022-01-18
  • 2021-12-20
猜你喜欢
  • 2021-12-06
  • 2022-12-23
  • 2022-01-18
相关资源
相似解决方案