When doing certain effects, a certain style of the same node may be continuously switched, that is, mutually exclusive switching between addClass and removeClass, such as the interlaced color change effect
jQuery provides a toggleClass method Used to simplify this mutually exclusive logic, dynamically add and delete Class through the toggleClass method. One execution is equivalent to addClass, and another execution is equivalent to the removeClass
toggleClass() method: each element in the matched element set Add or remove one or more style classes, depending on whether the style class exists or the value of the toggle attribute. That is: delete (add) a class if it exists (does not exist)
toggleClass( className ): one or more (separated by spaces) used to toggle on each element in the matched element set ) Style class name
toggleClass( className, switch ): A Boolean value used to determine whether the style should be added or removed
toggleClass( [switch] ): A Boolean value used to determine whether the style should be added or removed
toggleClass( [switch] ): A Boolean value used to determine whether the style Boolean value of class addition or removal
toggleClass(function(index, class, switch) [, switch]): used to return the style class used to toggle on each element in the matched element set name of a function. Receive the index position of the element and the old style class of the element as parameters
Note:
toggleClass is a mutually exclusive logic, that is, by judging whether the specified Class name exists on the corresponding element, If there is, delete it, if not, add it
toggleClass will retain the original Class name and add it, separated by spaces
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>隔行换色</title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> <style type="text/css"> body,table,td,{ font-family: Arial, Helvetica, sans-serif; font-size: 12px; } .h { background: #f3f3f3; color: #000; } .c { background: #ebebeb; color: #000; } </style> </head> <body> <table id="table" width="50%" border="0" cellpadding="3" cellspacing="1"> <tr> <td>php中文网</td> <td>php.cn</td> </tr> <tr> <td>php中文网</td> <td>php.cn</td> </tr> <tr> <td>php中文网</td> <td>php.cn</td> </tr> <tr> <td>php中文网</td> <td>php.cn</td> </tr> <tr> <td>php中文网</td> <td>php.cn</td> </tr> </table> </div> <script type="text/javascript"> //给所有的tr元素加一个class="c"的样式 $("#table tr").toggleClass("c"); </script> <script type="text/javascript"> //给所有的偶数tr元素切换class="c"的样式 //所有基数的样式保留,偶数的被删除 $("#table tr:odd").toggleClass("c"); </script> <script type="text/javascript"> //第二个参数判断样式类是否应该被添加或删除 //true,那么这个样式类将被添加; //false,那么这个样式类将被移除 //所有的奇数tr元素,应该都保留class="c"样式 $("#table tr:even").toggleClass("c", true); //这个操作没有变化,因为样式已经是存在的 </script> </body> </html>######Next Section