toggleClass(fn, [switch])
version 1.4 以降
解説
要素のクラスを、指定した関数が返す CSS クラスで切り替えます。
指定されたクラスが設定されていれば、そのクラスを削除します。
指定されたクラスが設定されていなければ、そのクラスを追加します。
引数
-
fn
Function: CSS クラス名を返す関数
このコールバック関数には、要素のインデックスと、現在のHTMLの内容が渡されます。
function (index, class) {
index;
class;
return class;
}
-
[switch]オプション
Boolean: クラスを追加する場合は true 、削除する場合は false
戻り値
関連
例
例1:クリックする度に、配列 colors の内容で、クラスを切り替えます。
.green { borderbackground-color: #dcffdc; borderborder: 1px solid #006400; }
.yellow { borderbackground-color: #fffacd; borderborder: 1px solid #daa520; }
.red { borderbackground-color: #ffe4e1; borderborder: 1px solid #b22222; }
var colors = ["green", "yellow", "red", ""];
var count = 0;
$("#block1").click(function(index, class) {
$(this).toggleClass(function() {
var index = count++ % colors.length;
return index == colors.length-1 ? colors.join(" ") : colors[index];
});
});
|