当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


JQuery toggleClass()用法及代码示例

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>

输出:

jquery-39

示例 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-40



相关用法


注:本文由纯净天空筛选整理自kundankumarjha大神的英文原创作品 jQuery toggleClass() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。