toggleClass()方法是jQuery中的一个内置方法,用于切换或更改附加到选定元素的类。
null
语法:
$(selector).toggleClass(class, function, switch)
参数: 该方法接受上述三个参数,如下所述:
- 课程: 它是必需的参数,用于指定需要替换的类名。
- 功能: 它是可选参数,用于指定返回一个或多个类名的函数。此参数包含元素的索引位置和元素的类名。
- 开关: 它是可选参数,用于指定true或false。默认情况下,这是真的。
返回值: 此方法返回所选元素,其中包含toggleClass()方法所做的指定更改。
以下示例说明了jQuery中的toggleClass()方法:
例1:
<!DOCTYPE html> < html > < head > < title >The toggleclass Method</ title > < script src = </ script > <!-- jQuery code to show the working of this method --> < script > $(document).ready(function() { $("button").click(function() { $("div").toggleClass("gfg"); }); }); </ script > < style > .gfg { font-size: 25px; background-color: yellow; min-height:120px; } div { width: 200px; min-height: 120px; background-color: lightgreen; padding: 20px; font-weight: bold; font-size: 20px; } </ style > </ head > < body > <!-- click inside this div element to see the change --> < div > < p >Hello!</ p > < p >Welcome to GeeksforGeeks.!</ p > < button >Click Here!</ button > </ div > </ body > </ html > |
输出:
例2:
<!DOCTYPE html> < html > < head > < title >toggle class property</ title > < script src = </ script > <!-- jQuery code to show the working of this method --> < script > $(document).ready(function() { $("button").click(function() { $("div").toggleClass(function(n) { n = 1; return "item_" + n; }); }); }); </ script > < style > .item_1 { color: green; font-weight: bold; font-size: 20px; background-color: white; border: 2px solid green; } div { text-align:center; width: 200px; min-height: 100px; background-color: lightgreen; padding: 20px; border: 2px solid black; font-weight: bold; } </ style > </ head > < body > <!-- click inside this div element --> < div > < p >Welcome to GeeksforGeeks!</ p > < button >Click Here!</ button > </ div > </ body > </ html > |
输出:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END