3-6 控制类名(className 属性)
本节编程练习不计算学习进度,请电脑登录imooc.com操作

控制类名(className 属性)

className 属性设置或返回元素的class 属性。

语法:

object.className = classname

作用:

1.获取元素的class 属性

2. 为网页内的某个元素指定一个css样式来更改该元素的外观

看看下面代码,获得 <p> 元素的 class 属性和改变className:

结果:

任务

我们通过className属性来设置元素的样式:

1.在右边编辑第33行补充代码,给id="p1"元素通过className添加"类名为one"的样式。当点击"添加样式"按钮,第一段文字添加样式。

2.在右边编辑第37行补充代码,给id="p2"元素通过className修改为"类名为two"的样式。当点击"更改外观"按钮,第二段文字更改样式。

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  5. <title>className属性</title>
  6. <style>
  7. body{ font-size:16px;}
  8. .one{
  9. border:1px solid #eee;
  10. width:230px;
  11. height:50px;
  12. background:#ccc;
  13. color:red;
  14. }
  15. .two{
  16. border:1px solid #ccc;
  17. width:230px;
  18. height:50px;
  19. background:#9CF;
  20. color:blue;
  21. }
  22. </style>
  23. </head>
  24. <body>
  25. <p id="p1" > JavaScript使网页显示动态效果并实现与用户交互功能。</p>
  26. <input type="button" value="添加样式" onclick="add()"/>
  27. <p id="p2" class="one">JavaScript使网页显示动态效果并实现与用户交互功能。</p>
  28. <input type="button" value="更改外观" onclick="modify()"/>
  29.  
  30. <script type="text/javascript">
  31. function add(){
  32. var p1 = document.getElementById("p1");
  33.  
  34. }
  35. function modify(){
  36. var p2 = document.getElementById("p2");
  37.  
  38. }
  39. </script>
  40. </body>
  41. </html>
下一节