$(selector).toggleClass(classname,function(index,currentclass),switch)
参数 | 说明 |
classname | 这是强制性参数。它指定一个或多个要添加或删除的类名。如果您使用多个类,请按空格将其分隔。 |
function(index,currentclass),switch) | 这是一个可选参数。它指定要添加或删除的一个或多个类名。 index:它提供元素在集合中的索引位置。 currentclass:它提供所选元素的当前类别名称。 |
switch | 它也是一个可选参数。这是一个布尔值,它指定是应添加类(true)还是应删除类(false)。 |
<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggleClass("main");
});
});
</script>
<style>
.main {
font-size: 150%;
color: red;
}
</style>
</head>
<body>
<button>Toggle class "main" for p elements</button>
<p>Hello! bianchenghao6.com</p>
<p>This is popular tutorial website.</p>
<p><b>Note:</b> Click repeatedly on the button to see the toggle effect.</p>
</body>
</html>
Hello! bianchenghao6.com
This is popular tutorial website.
Note: Click repeatedly on the button to see the toggle effect.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>toggleClass demo</title>
<style>
p {
margin: 4px;
font-size: 16px;
font-weight: bolder;
cursor: pointer;
}
.blue {
color: black;
}
.highlight {
background: pink;
}
</style>
<script src="/jquery-1.10.2.js"></script>
</head>
<body>
<p class="blue highlight">bianchenghao6.com</p>
<p class="blue">Java Tutorial</p>
<p class="blue">SQL Tutorial</p>
<p class="blue">Android Tutorial</p>
<p class="blue">HTML Tutorial</p>
<p class="blue">etc.</p>
<script>
$("p").click(function() {
$( this ).toggleClass( "highlight");
});
</script>
</body>
</html>
bianchenghao6.com
Java Tutorial
SQL Tutorial
Android Tutorial
HTML Tutorial
etc.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>toggleClass demo</title>
<style>
.wrap > div {
float: left;
width: 100px;
margin: 1em 1em 0 0;
padding=left: 3px;
border: 1px solid #abc;
}
div.a {
background-color: aqua;
}
div.b {
background-color: burlywood;
}
div.c {
background-color: cornsilk;
}
</style>
<script src="/jquery-1.10.2.js"></script>
</head>
<body>
<div class="buttons">
<button>toggle</button>
<button class="a">toggle a</button>
<button class="a b">toggle a b</button>
<button class="a b c">toggle a b c</button>
<a href="#">Reset</a>
</div>
<div class="wrap">
<div></div>
<div class="b"></div>
<div class="a b"></div>
<div class="a c"></div>
</div>
<script>
var cls = [ "", "a", "a b", "a b c" ];
var divs = $("div.wrap").children();
var appendClass = function() {
divs.append(function() {
return "<div>" + ( this.className || "none") + "</div>";
});
};
appendClass();
$("button").on( "click", function() {
var tc = this.className || undefined;
divs.toggleClass( tc );
appendClass();
});
$("a").on( "click", function( event ) {
event.preventDefault();
divs.empty().each(function( i ) {
this.className = cls[ i ];
});
appendClass();
});
</script>
</body>
</html>