jQuery .toggleClass():切换类或指定类的状态

.toggleClass("active") 会移除已有的 active,或在没有该类时添加它。.toggleClass("active", enabled) 在 enabled 为 true 时添加,为 false 时移除。前者用于反转,后者用于反映已知状态。

切换类和指定状态的语法

类名无需点号。状态参数必须是布尔值 true 或 false。字符串 "false" 和数字 0 不按布尔状态处理。以下三行是独立的调用示例。jQuery API — .toggleClass()

$("#by-button").toggleClass("active");
$("#by-button").toggleClass("active", true);
$("#by-button").toggleClass("active", false);

运行示例,用按钮反转高亮

将完整代码以 UTF-8 保存为 jquery-toggleclass.html 并打开。示例从官方 CDN 加载 jQuery 4.0.0,需要联网。按钮控制第一段,复选框控制第二段。

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery .toggleClass() 示例</title>
  <style>
    body { margin: 24px; font: 1rem/1.6 system-ui, sans-serif; overflow-wrap: anywhere; }
    button, input { font: inherit; }
    .base { padding: .65rem; border: 2px solid #a1a7ad; border-radius: .4rem; }
    .active { background: #fff0b3; border-color: #08716d; font-weight: 700; }
  </style>
  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
  <main>
    <h1>jQuery .toggleClass() 示例</h1>
    <button id="toggle" type="button" aria-pressed="false">用按钮切换高亮</button>
    <p id="by-button" class="base">由按钮控制的段落</p>
    <p id="button-state" role="status"></p>
    <label><input id="option" type="checkbox"> 根据复选框高亮</label>
    <p id="by-option" class="base">跟随复选框状态的段落</p>
    <p id="option-state" role="status"></p>
  </main>
  <script>
    $(function () {
      const $button = $("#toggle");
      const $option = $("#option");
      const $byButton = $("#by-button");
      const $byOption = $("#by-option");
      const on = "高亮开启";
      const off = "高亮关闭";

      function showButtonState() {
        const enabled = $byButton.hasClass("active");
        $button.attr("aria-pressed", String(enabled));
        $("#button-state").text(enabled ? on : off);
      }

      function syncOption() {
        const enabled = $option.prop("checked");
        $byOption.toggleClass("active", enabled);
        $("#option-state").text(enabled ? on : off);
      }

      $button.on("click", function () {
        $byButton.toggleClass("active");
        showButtonState();
      });

      $option.on("change", syncOption);
      showButtonState();
      syncOption();
    });
  </script>
</body>
</html>

按一次按钮,第一段高亮,状态显示“高亮开启”。再按一次会移除 active。也可用 Tab 聚焦按钮,再按回车键或空格键测试。

让高亮跟随复选框状态

勾选复选框会给第二段添加 active,取消勾选会移除它。代码直接传入 .prop("checked") 读到的布尔值。在勾选状态相同的情况下重复同步,高亮不会反转。初始化时同步一次,也能让显示匹配复选框。

切换按钮保留原标签,用 aria-pressed 表示当前状态。原生复选框本身就会提供勾选状态。只修改 CSS 类不会更新无障碍属性。WAI-ARIA APG — Button Pattern

切换多个类名

多个名称可用空格分隔,jQuery 3.3 起也支持数组。没有状态参数时,每个类名独立反转。在控制台运行以下代码,第一次调用会移除 active 并添加 marked,下一次调用让两个类都存在。

const $item = $('<p class="base active"></p>');
$item.toggleClass("active marked");
console.log($item.attr("class")); // base marked
$item.toggleClass(["active", "marked"], true);
console.log($item.attr("class")); // base marked active

jQuery 4.0 的变化与排查

jQuery 4.0 移除了未指定类名的 .toggleClass() 和 .toggleClass(state)。这些旧形式会操作整个类列表。4.0 仍然支持 .toggleClass("active", state)。jQuery 4.0 Upgrade Guide

如果结果不符预期,先在元素面板检查类是否变化,以及状态值是否为布尔值。类变了但外观不变时,检查 CSS 规则和优先级。需要始终添加或移除时,用 .addClass() 或 .removeClass()。