.toggleClass(className) vráti: jQuery
Prida alebo odstrani triedu z kazdeho zo zvolenych prvkov, v zavislosti na pritomnosti triedy alebo hodnoty pre argument prepinaca.
Tato metoda prijma ako parameter jeden alebo viac tried. V prvej verzii, ak zvoleny element uz ma triedu, potom bude odstranena; ak element nema triedu, potom bude pridana.Napriklad, mozme pouzit .toggleClass() na jednoduchy <div>
Some text.
Prvym pouzitim $('div.tumble').toggleClass('bounce')
dostaneme:
Some text.
Druhym pouzitim $('div.tumble').toggleClass('bounce')
, <div>
trieda vrati samotnu tumble
hodnotu:
Some text.
Applying .toggleClass('bounce spin')
to the same <div>
alternates between <div class="tumble bounce spin">
and <div class="tumble">
.
The second version of .toggleClass() uses the second parameter for determining whether the class should be added or removed. If this parameter's value is true, then the class is added; if false, the class is removed. In essence, the statement:
$('#foo').toggleClass(className, addOrRemove);
je ekvivalent k:
if (addOrRemove) { $('#foo').addClass(className); } else { $('#foo').removeClass(className); }
$('div.foo').toggleClass(function() { if ($(this).parent().is('.bar') { return 'happy'; } else { return 'sad'; } });
Tento priklad bude menit happy
triedu pre <div class="foo">
element ak jeho rodicovsky element ma triedu bar
; inak bude prepinat sad
triedu.
Priklady:
Prepne triedu 'highlight' ked je kliknute na odstavec.
<!DOCTYPE html> <html> <head> <style> p { margin: 4px; font-size:16px; font-weight:bolder; cursor:pointer; } .blue { color:blue; } .highlight { background:yellow; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <p class="blue">Click to toggle</p> <p class="blue highlight">highlight</p> <p class="blue">on these</p> <p class="blue">paragraphs</p> <script> $("p").click(function () { $(this).toggleClass("highlight"); }); </script> </body> </html>
Prida 'highlight' triedu po kazdom tretom kliknuti na odstavec, a odstrani kazdy prvym a druhym kliknutim.
<!DOCTYPE html> <html> <head> <style> p { margin: 4px; font-size:16px; font-weight:bolder; cursor:pointer; } .blue { color:blue; } .highlight { background:red; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <p class="blue">Click to toggle (<span>clicks: 0</span>)</p> <p class="blue highlight">highlight (<span>clicks: 0</span>)</p> <p class="blue">on these (<span>clicks: 0</span>)</p> <p class="blue">paragraphs (<span>clicks: 0</span>)</p> <script> var count = 0; $("p").each(function() { var $thisParagraph = $(this); var count = 0; $thisParagraph.click(function() { count++; $thisParagraph.find("span").text('clicks: ' + count); $thisParagraph.toggleClass("highlight", count % 3 == 0); }); }); </script> </body> </html>