jQueryのtoggleClass()メソッド

❮jQueryHTML/ CSSメソッド

すべての<p>要素の「メイン」クラス名の追加と削除を切り替えます。

$("button").click(function(){
  $("p").toggleClass("main");
});

定義と使用法

tokenClass()メソッドは、選択した要素から1つ以上のクラス名を追加するか削除するかを切り替えます。

このメソッドは、指定されたクラス名について各要素をチェックします。クラス名は、欠落している場合は追加され、すでに設定されている場合は削除されます-これにより、トグル効果が作成されます。

ただし、「switch」パラメーターを使用すると、クラス名のみを削除するか、追加するかを指定できます。


構文

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

Parameter Description
classname Required. Specifies one or more class names to add or remove. To specify several classes, separate the class names with a space
function(index,currentclass) Optional. Specifies a function that returns one or more class names to add/remove
  • index - Returns the index position of the element in the set
  • currentclass - Returns current class name of selected elements
switch Optional. A Boolean value specifying if the class should only be added (true), or only be removed (false)

自分で試してみてください-例


の追加と削除を切り替えるtoggleClass()メソッドを使用して、クラス名の追加と削除を切り替える方法。


を使用してクラスを切り替える関数を使用して、選択した要素に対して切り替えるクラス名を指定します。


を使用してクラス名のみを追加または削除する方法。


❮jQueryHTML/ CSSメソッド