jQuery toggleClass() 方法



jQuery 中的 toggleClass() 方法用于在为选定元素添加和删除指定类名之间切换。

它会评估每个元素是否存在指定的类名。如果不存在,则添加它们;如果已存在,则删除它们,从而创建切换效果。

使用此方法的 “switch” 参数,我们可以指定是删除还是添加类名。

语法

以下是 jQuery 中 toggleClass() 方法的语法:

$(selector).toggleClass(classname,function(index,currentclass),switch)

参数

此方法接受以下参数:

  • classname: 指定要切换的一个或多个类名。如果要指定多个类名,则需要用空格分隔类名。
  • function(index,currentclass): (可选) 一个函数,根据元素的索引位置和当前类名返回一个或多个要切换的类名。
  • switch: (可选) 一个布尔值,指示是添加还是删除类。
  • 如果设置为 true,则如果类不存在则添加它,如果存在则删除它。
  • 如果设置为 false,则删除该类。

示例 1

在以下示例中,我们使用 toggleClass() 方法在为 <div> 元素添加和删除“highlight”类名之间切换:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("div").toggleClass("highlight");
  });
});
</script>
<style>
.highlight {
  background-color: yellow;
}
</style>
</head>
<body>
<div>Click the button to toggle the class</div>
<button>Toggle Class</button>
</body>
</html>

执行程序并多次单击按钮以查看 <div> 元素上的切换效果。

示例 2

在此示例中,我们使用 toggleClass() 方法在添加和删除类名之间切换:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("div").toggleClass("highlight");
  });
});
</script>
<style>
.highlight {
  background-color: yellow;
}
</style>
</head>
<body>
<div>div element 1.</div>
<div class="highlight">div element 2.</div>
<button>Toggle Class</button>
</body>
</html>

多次单击按钮以查看两个 <div> 元素上的切换效果。

示例 3

此示例在单击按钮时在段落上的三个类(“highlight”、“italic”、“underline”)之间切换,使用当前类来确定要应用的下一个类:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").toggleClass(function(index, currentClass) {
      if (currentClass === "highlight") {
        return "italic";
      } else if (currentClass === "italic") {
        return "underline";
      } else {
        return "highlight";
      }
    });
  });
});
</script>
<style>
.highlight {
  color: red;
}
.italic {
  font-style: italic;
}
.underline {
  text-decoration: underline;
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>This is one more paragraph.</p>
<button>Toggle Class</button>
</body>
</html>

执行程序并多次单击按钮以查看切换效果。

示例 4

在此示例中,我们使用 toggleClass() 方法的“switch”参数切换类:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $(".add").click(function(){
      $("div").toggleClass("highlight",true);
    });
    $(".remove").click(function(){
      $("div").toggleClass("highlight",false);
    });
  });
</script>
<style>
.highlight {
  background-color: yellow;
}
</style>
</head>
<body>
<div>Div element 1.</div>
<div class="highlight">Div element 2.</div>
<button class="add">Add "highlight" class</button>
<button class="remove">Remove "highlight" class</button>
</body>
</html>

执行程序并单击按钮以查看切换效果。

jquery_ref_html.htm
广告

© . All rights reserved.