jQuery 的 switchClass() 方法和 toggleClass() 方法有哪些不同?
switchClass() 用於切換元素的 class。使用它來替換一個 class 為另一個。將 jQuery UI 庫新增到網頁以使用 switchClass()。
示例
你可以嘗試執行以下程式碼來學習如何使用 switch class −
<html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a").click(function(){ $("a.active").removeClass("active"); $(this).addClass("active"); }); }); </script> <style> .active { font-size: 22px; } </style> </head> <body> <a href="#" class="demo1">One</a> <a href="#" class="demo2">Two</a> <p>Click any of the link above and you can see the changes.</p> </body> </html>
切換類
如果你想在類之間切換,可以使用 toggleClass()。這是為了在選定的元素中新增或刪除類。
示例
你可以嘗試執行以下程式碼來學習如何切換類 −
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1, p").toggleClass("blue"); }); }); </script> <style> .blue { color: blue; } </style> </head> <body> <h1>Heading 1</h1> <p>This is demo text.</p> <button>Toggle</button> </body> </html>
廣告