jquery add class remove class

jQuery has several methods for CSS manipulation. We will look at the following methods:

  • addClass() – Adds one or more classes to the selected elements
  • removeClass() – Removes one or more classes from the selected elements
  • toggleClass() – Toggles between adding/removing classes from the selected elements
  • css() – Sets or returns the style attribute

新增 class 範例:

$(“button”).click(function(){
  $(“div”).addClass(“important”);
});

移除 class 範例:

$(“button”).click(function(){
  $(“div”).removeClass(“blue”);
});

比較常見的是用切換某一個屬性, 可以用 toggle

$(“button”).click(function(){
  $(“h1, h2, p”).toggleClass(“blue”);
});

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *