jQuery toggleClass()的应用实例

jQuery toggleClass()的应用实例

toggleClass()方法是jQuery内置的一个方法,用于切换或改变所选元素的类别。

语法:

$(selector).toggleClass(class, function, switch)

参数:该方法接受上面提到的和下面描述的三个参数。

  • class。这是必要的参数,用于指定需要替换的类名。
  • function。这是一个可选参数,用于指定一个返回一个或多个类名的函数。这个参数包含元素的索引位置和元素的类名。
  • switch。这是一个可选参数,用于指定真或假。默认情况下,它是真。

返回值:该方法返回选定的元素,以及toggleClass()方法所做的指定修改。

下面的例子说明了jQuery中的toggleClass()方法。

示例 1:

<!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 toggleClass()的应用实例

示例 2:

<!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()的应用实例

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程