返回值:jQueryaddClass(className)

为每个匹配的元素添加指定的 CSS 样式。

需要特别注意的是,该方法不会替换原有的样式,仅仅是在匹配的元素中添加样式。

可以为匹配到元素一次添加多个样式,样式之间用空格分隔。例如:

$("p").addClass("myClass yourClass");

该方法通常和 .removeClass() 一起使用,用来切换元素的样式。例如:

$("p").removeClass("myClass noClass").addClass("yourClass");

在这里,所有段落标签中的 myClassnoClass 样式会被移除,取而代之的是 yourClass 样式。

从 jQuery 1.4 开始,.addClass() 方法的参数可以是一个函数。

$("ul li:last").addClass(function(index) {
  return "item-" + index;
});

上面的例子中,会在一个含有 5 个 <li> 的无序列表中,为最后一个 <li> 添加 "item-4" 样式。

示例:

为匹配的元素添加 "selected" 样式。

<!DOCTYPE html>
<html>
<head>
<style>
  p { margin: 8px; font-size:16px; }
  .selected { color:blue; }
  .highlight { background:yellow; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>


  <p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>
  

<script>


  $("p:last").addClass("selected");
  

</script>
</body>
</html>

演示:

示例:

为匹配的元素添加 "selected" 和 "highlight" 样式。

<!DOCTYPE html>
<html>
<head>
<style>
  p { margin: 8px; font-size:16px; }
  .selected { color:red; }
  .highlight { background:yellow; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>

<script>


  $("p:last").addClass("selected highlight");
  

</script>
</body>
</html>

演示:

示例:

将一个函数作为 .addClass() 的参数,为已有 "red" 样式的 div 添加 "green" 样式。

<!DOCTYPE html>
<html>
<head>
<style>
  div { background: white; }
  .red { background: red; }
  .red.green { background: green; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>


 <div>This div should be white</div>
 <div class="red">This div will be green because it now has the "green" and "red" classes.
   It would be red if the addClass function failed.</div>
 <div>This div should be white</div>
 <p>There are zero green divs</p>


<script>


  $("div").addClass(function(index, currentClass) {
    var addedClass;

    if ( currentClass === "red" ) {
      addedClass = "green";
      $("p").text("There is one green div");
    }
  
    return addedClass;
  });


</script>
</body>
</html>

演示: