jQuery - toggleClass( class ) 方法



描述

toggleClass( class ) 方法用于添加指定的类(如果不存在),或删除指定的类(如果存在)。

语法

以下是使用此方法的简单语法:

selector.toggleClass( class )

参数

以下是此方法使用到的所有参数的描述:

  • class − CSS 类名。

示例

以下示例演示了如何通过单击一次来移除一个类,再次单击则重新添加同一个类:

<html>
   <head>
      <title>The Selecter Example</title>
      <script type = "text/javascript" 
         src = "https://tutorialspoint.com/jquery/jquery-3.6.0.js">
      </script>
   
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("p#pid").click(function () {
               $(this).toggleClass("red");
            });
         });
      </script>
		
      <style>
         .red { color:red; }
      </style>
   </head>
	
   <body>
      <p class = "green">Click following line to see the result</p>
      <p class = "red" id = "pid">This is first paragraph.</p>
   </body>
</html>

这将产生以下结果:

jquery-attributes.htm
广告
© . All rights reserved.