Discuz教程网

js中设置元素class的三种方法小结

[复制链接]
authicon dly 发表于 2011-9-6 21:13:19 | 显示全部楼层 |阅读模式
一、el.setAttribute('class','abc');

  1. <!DOCTYPE HTML>
  2. <HTML>
  3. <HEAD>
  4. <meta charset="utf-8" />
  5. <title>setAttribute('class', 'abc')</title>
  6. <style type="text/css">
  7. .abc {
  8. background: red;
  9. }
  10. </style>
  11. </HEAD>
  12. <BODY>
  13. <div id="d1">test div</div>
  14. <script>
  15. var div = document.getElementById('d1');
  16. div.setAttribute("class", "abc");
  17. </script>
  18. </BODY>
  19. </HTML>
复制代码

IE6/7 : div背景色不是红色
IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色为红色
结果:IE6/7不支持setAttribute('class',xxx)方式设置元素的class。
二、el.setAttribute('className', 'abc')


  1. <!DOCTYPE HTML>
  2. <HTML>
  3. <HEAD>
  4. <meta charset="utf-8" />
  5. <title>setAttribute('className', 'abc')</title>
  6. <style type="text/css">
  7. .abc {
  8. background: red;
  9. }
  10. </style>
  11. </HEAD>
  12. <BODY>
  13. <div id="d1">test div</div>
  14. <script>
  15. var div = document.getElementById('d1');
  16. div.setAttribute("className", "abc");
  17. </script>
  18. </BODY>
  19. </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';

  1. <!DOCTYPE HTML>
  2. <HTML>
  3. <HEAD>
  4. <meta charset="utf-8" />
  5. <title>el.className = 'abc'</title>
  6. <style type="text/css">
  7. .abc {
  8. background: red;
  9. }
  10. </style>
  11. </HEAD>
  12. <BODY>
  13. <div id="d1">test div</div>
  14. <script>
  15. var div = document.getElementById('d1');
  16. div.className = 'abc';
  17. </script>
  18. </BODY>
  19. </HTML>
复制代码

所有浏览器都支持。





上一篇:dojo学习第一天 Tab选项卡 实现
下一篇:ASP网站出现 msxml3.dll 错误 80072ee7 错误的解决方法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-7-10 02:24

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表