How to use .toggleClass () in javascript
This article mainly introduces how to use. ToggleClass () in javascript. It is very detailed and has certain reference value. If you are interested, you must finish reading it.
If the parent element of the matching element has a bar style class name, this example will switch the happy style class for the element; otherwise, it will switch the sad style class.
Example:
Example: when clicking on a paragraph, there is a switch to the 'highlight' style class.
P {margin: 4px; font-size:16px; font-weight:bolder
Cursor:pointer;}
.blue {color:blue;}
.highlight {background:yellow;}
Click to toggle
Highlight
On these
Paragraphs
$("p") .click (function () {
$(this) .toggleClass ("highlight")
})
Example: add the "highlight" style class every time you click on the paragraph the third time, and remove the "highlight" style class on the first and second clicks
P {margin: 4px; font-size:16px; font-weight:bolder
Cursor:pointer;}
.blue {color:blue;}
.highlight {background:red;}
Click to toggle (clicks: 0)
Highlight (clicks: 0)
On these (clicks: 0)
Paragraphs (clicks: 0)
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)
})
})
Example: Toggle the class name (s) indicated on the buttons for each div.
Wrap > div {float: left; width: 100px; margin: 1em 1em 00
Padding=left: 3px; border: 1px solid # abc;}
Div.a {background-color: aqua;}
Div.b {background-color: burlywood;}
Div.c {background-color: cornsilk;}
Toggle
Toggle a
Toggle a b
Toggle a b c
Reset
Var cls = ['','a','a baked,'a b c']
Var divs = $('div.wrap') .children ()
Var appendClass = function () {
Divs.append (function () {
Return''+ (this.className | | 'none') +'
})
}
AppendClass ()
$('button'). Bind (' click', function () {
Var tc = this.className | | undefined
Divs.toggleClass (tc)
AppendClass ()
})
$('a'). Bind ('click', function (event) {
Event.preventDefault ()
Divs.empty () .each (function (I) {
This.className = cls [I]
})
AppendClass ()
})
The above is all the content of the article "how to use .toggleClass () in javascript". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!