萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery removeClass() 方法批量移除指定 Class 完整指南

jQuery removeClass() 精準移除元素 Class 技巧全解析

removeClass() 方法能從匹配元素中移除一個或多個指定的 CSS 類名,是實現狀態重置、樣式切換、表單驗證提示清除等場景的核心工具。

核心用法詳解

// 移除單個 class
$(selector).removeClass("class-name");

// 移除多個 class(空格分隔)
$(selector).removeClass("class1 class2 class3");

// 移除所有 class
$(selector).removeClass();

// 使用函數條件移除
$(selector).removeClass(function(index, currentClass) {
  return index % 2 === 0 ? "even" : "odd";
});

完整代碼範例

點擊按鈕移除所有標題與段落的 red class:

<!DOCTYPE html>
<html>
<head>
  <script src="js/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("h1, h2, p").removeClass("red");
      });
    });
  </script>
  <style type="text/css">
    .red { color: red; font-weight: bold; }
    .important { font-weight: bold; font-size: xx-large; }
    .blue { color: blue; }
  </style>
</head>
<body>
  <h1 class="red">Heading 1</h1>
  <h2 class="red">Heading 2</h2>
  <p class="red">This is a paragraph.</p>
  <p>This is another paragraph.</p>
  <br>
  <button>Remove class from elements</button>
</body>
</html>

實戰應用場景

  1. 表單驗證重置:提交前 removeClass("error success") 清除舊提示
  2. 標籤頁切換:切換前 removeClass("active") 重置所有標籤
  3. 動畫結束清理:.animate(...).promise().done(() => $el.removeClass("animating"))
  4. 主題切換:$("body").removeClass("theme-dark theme-blue").addClass("theme-light")

配合 toggleClass 實現更優雅的切換

// 代替手動判斷
if ($el.hasClass("open")) $el.removeClass("open");
else $el.addClass("open");

// 直接使用
$el.toggleClass("open");

removeClass() 與 addClass()、toggleClass() 組成了 jQuery 類名操作的「鐵三角」,熟練掌握它們的組合用法能讓 DOM 樣式控制得心應手。

copyright © 萬盛學電腦網 all rights reserved