toggleClass() 方法是 jQuery 中的内置方法,用于切换或更改附加到所选元素的类。
用法:
$(selector).toggleClass(class, function, switch)
参数:
该方法接受如上所述和如下所述的三个参数:
- class:为必填参数,用于指定需要替换的类名。
- function:它是一个可选参数,用于指定返回一个或多个类名的函数。该参数包含元素的索引位置和元素的类名。
- switch:它是一个可选参数,用于指定 true 或 false。默认情况下是 true。
返回值:此方法返回具有 toggleClass() 方法所做的指定更改的选定元素。
以下示例说明了 jQuery 中的 toggleClass() 方法:
示例 1:
html
<!DOCTYPE html>
<html>
<head>
<title>The toggleclass Method</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</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:
html
<!DOCTYPE html>
<html>
<head>
<title>toggle class property</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</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>
输出:
相关用法
- JQuery toggleClass()用法及代码示例
- JQuery toggle()用法及代码示例
- JQuery toArray()用法及代码示例
- JQuery text()用法及代码示例
- JQuery trigger()用法及代码示例
- JQuery triggerHandler()用法及代码示例
- JQuery type()用法及代码示例
- JQuery trim()用法及代码示例
- JQuery andSelf()用法及代码示例
- JQuery change()用法及代码示例
- JQuery each()用法及代码示例
- JQuery end()用法及代码示例
- JQuery fadeOut()用法及代码示例
- JQuery height()用法及代码示例
- JQuery innerHeight()用法及代码示例
- JQuery keydown()用法及代码示例
- JQuery keypress()用法及代码示例
- JQuery next()用法及代码示例
- JQuery nextAll()用法及代码示例
- JQuery parent()用法及代码示例
- JQuery parents()用法及代码示例
- JQuery prev()用法及代码示例
- JQuery prevAll()用法及代码示例
- JQuery remove()用法及代码示例
- JQuery show()用法及代码示例
注:本文由纯净天空筛选整理自kundankumarjha大神的英文原创作品 jQuery toggleClass() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。