在运用 jQuery 的时候我们经常需要动态的给一些 dom 元素添加 CSS 样式, 下面我们来看一下 jQuery 如何动态的添加 CSS 样式.
1, 使用 addClass() 方法添加 CSS
addClass() 方法向被选元素添加一个或多个类.
该方法不会移除已存在的 class 属性, 仅仅添加一个或多个 class 属性.
提示: 如需添加多个类, 请使用空格分隔类名.
语法:
$(selector).addClass(class)
示例:
- <html>
- <head>
- <script type="text/javascript" src="/jquery/jquery.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- $("button").click(function(){
- $("p:first").addClass("intro");
- });
- });
- </script>
- <style type="text/css">
- .intro
- {
- font-size:120%;
- color:red;
- }
- </style>
- </head>
- <body>
- <h1>This is a heading</h1>
- <p>This is a paragraph.</p>
- <p>This is another paragraph.</p>
- <button > 向第一个 p 元素添加一个类 </button>
- </body>
- </HTML>
2, 使用 toggleClass() 方法添加
toggleClass() 对设置或移除被选元素的一个或多个类进行切换.
该方法检查每个元素中指定的类. 如果不存在则添加类, 如果已设置则删除之. 这就是所谓的切换效果.
不过, 通过使用 "switch" 参数, 您能够规定只删除或只添加类.
语法:
$(selector).toggleClass(class,switch)
示例:
- <HTML>
- <head>
- <script type="text/javascript" src="/jquery/jquery.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- $("button").click(function(){
- $("p").toggleClass("main");
- });
- });
- </script>
- <style type="text/css">
- .main
- {
- font-size:120%;
- color:red;
- }
- </style>
- </head>
- <body>
- <h1 id="h1">This is a heading</h1>
- <p>This is a paragraph.</p>
- <p>This is another paragraph.</p>
- <button class="btn1"> 切换段落的 "main" 类 </button>
- </body>
- </HTML>
推荐学习: JavaScript 视频教程 https://www.html.cn/js/javascript/video/ !!
来源: http://www.css88.com/qa/javascript/14916.html