jQuery - toggleClass( class ) 方法



描述

toggleClass( class ) 方法用於新增指定的類(如果不存在),或刪除指定的類(如果存在)。

語法

以下是使用此方法的簡單語法:

selector.toggleClass( class )

引數

以下是此方法使用到的所有引數的描述:

  • class − CSS 類名。

示例

以下示例演示瞭如何透過單擊一次來移除一個類,再次單擊則重新新增同一個類:

<html>
   <head>
      <title>The Selecter Example</title>
      <script type = "text/javascript" 
         src = "https://tutorialspoint.tw/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.