jQuery动态添加和删除class属性

Linux大全评论2.5K views阅读模式

在用jQuery时,遇到一个问题,就是如何动态得添加和删除class的属性,下面是我的解决代码:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>测试</title>  
  6. <script type="text/javascript" src="jquery-1.7.2.js"></script>  
  7. <script type="text/javascript">  
  8. $(document).ready(function(){  
  9.   $("button").click(function(){  
  10.       
  11.     $("p:first").addClass("intro");  
  12.     $("p:first").removeClass("default");  
  13.   });  
  14. });  
  15. </script>  
  16. <style type="text/css">  
  17. .intro  
  18. {  
  19. font-size:120%;  
  20. color:red;  
  21. }  
  22. .default  
  23. {  
  24.     font-size:16;  
  25.     color:#0F9;  
  26. }  
  27. </style>  
  28. </head>  
  29.   
  30. <body>  
  31. <h1>This is a heading</h1>  
  32. <p class="default">This is a paragraph.</p>  
  33. <p>This is another paragraph.</p>  
  34. <button>向第一个 p 元素添加一个类并删除一个类</button>  
  35. </body>  
  36. </html>  

效果如下:

点击前:

jQuery动态添加和删除class属性

企鹅博客
  • 本文由 发表于 2019年9月7日 14:21:49
  • 转载请务必保留本文链接:https://www.qieseo.com/175301.html

发表评论