jQuery 入门教程(16): 设置或取得元素的CSS class

jerry JQuery 2015年08月24日 收藏

jQuery支持方法用来操作HTML元素的CSS 属性
下面的方法为jQuery 提供的CSS操作方法:

  • addClass() – 为指定的元素添加一个或多个CSS类。
  • removeClass() – 为指定的元素删除一个或多个CSS类。
  • toggleClass() – 为指定的元素在添加/删除CSS类之间切换。
  • css() -设置或是取得CSS类型属性。

下面的StyleSheet为后面例子使用的CSS风格:

  1. .important
  2. {
  3. font-weight:bold;
  4. font-size:xx-large;
  5. }
  6.  
  7. .blue
  8. {
  9. color:blue;
  10. }

jQuery addClass示例
下面的例子为给定的元素添加CSS风格类

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JQuery Demo</title>
  6. <script src="scripts/jquery-1.9.1.js"></script>
  7.  
  8. <script>
  9. $(document).ready(function () {
  10. $("button").click(function () {
  11. $("h1,h2,p").addClass("blue");
  12. $("div").addClass("important");
  13. });
  14. });
  15. </script>
  16. <style type="text/css">
  17. .important
  18. {
  19. font-weight: bold;
  20. font-size: xx-large;
  21. }
  22.  
  23. .blue
  24. {
  25. color: blue;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30.  
  31. <h1>Heading 1</h1>
  32. <h2>Heading 2</h2>
  33. <p>This is a paragraph.</p>
  34. <p>This is another paragraph.</p>
  35. <div>This is some important text!</div>
  36. <br>
  37. <button>Add classes to elements</button>
  38.  
  39. </body>
  40. </html>

20130309007
你也可以在addClass 添加多个类的名称,如:

  1. $("button").click(function(){
  2. $("#div1").addClass("important blue");
  3. });

jQuery removeClass 示例

  1. $("button").click(function(){
  2. $("h1,h2,p").removeClass("blue");
  3. });

jQuery toggle()示例,下面的例子使用toggle为HTML元素在添加/删除CSS类blue之间切换

  1. $("button").click(function(){
  2. $("h1,h2,p").toggleClass("blue");
  3. });

下一篇介绍css()的用法。