jQuery attributes and styles (5)
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中文網(wǎng)</td> <td>php.cn</td> </tr> <tr> <td>php中文網(wǎng)</td> <td>php.cn</td> </tr> <tr> <td>php中文網(wǎng)</td> <td>php.cn</td> </tr> <tr> <td>php中文網(wǎng)</td> <td>php.cn</td> </tr> <tr> <td>php中文網(wǎng)</td> <td>php.cn</td> </tr> </table> </div> <script type="text/javascript"> //給所有的tr元素加一個(gè)class="c"的樣式 $("#table tr").toggleClass("c"); </script> <script type="text/javascript"> //給所有的偶數(shù)tr元素切換class="c"的樣式 //所有基數(shù)的樣式保留,偶數(shù)的被刪除 $("#table tr:odd").toggleClass("c"); </script> <script type="text/javascript"> //第二個(gè)參數(shù)判斷樣式類是否應(yīng)該被添加或刪除 //true,那么這個(gè)樣式類將被添加; //false,那么這個(gè)樣式類將被移除 //所有的奇數(shù)tr元素,應(yīng)該都保留class="c"樣式 $("#table tr:even").toggleClass("c", true); //這個(gè)操作沒(méi)有變化,因?yàn)闃邮揭呀?jīng)是存在的 </script> </body> </html>######