2024年06月13日
jquery:toggleClass()
このメソッドの説明
toggleClass() はjQueryメソッドです。
要素に指定クラスのCSSを追加したり、外したりする事により図形を変化させます。
メソッド
セレクタ.toggleClass( className , duration , complete )
パラメータ
className (文字列)(必須)
追加/削除するclass名を指定します。
複数指定したい場合はスペースで区切ります。
duration (整数)(省略可)
CSSの追加/削除の実行時間
初期値:0
指定方法は下記の文字列でも可
・'slow' :600ms
・'normal':400ms
・'fast' :200ms
complete (関数)(省略可)
CSSの追加/削除後に実行する関数
事例
1.BOXの背景色や色を変更する
| 下記のBOXをクリックして下さい。
BOXの文字色と背景色がトグルします。 Warning: include_once(/sample/javascript/animation/toggleClass/box): Failed to open stream: No such file or directory in /volume1/web/school/wp-content/themes/my_template/functions.php on line 44 Warning: include_once(): Failed opening '/sample/javascript/animation/toggleClass/box' for inclusion (include_path='.:/usr/share/pear') in /volume1/web/school/wp-content/themes/my_template/functions.php on line 44 |
上記は下記のプログラムで構成されています。
<div class='box'>click</div>
<style>
.box{
width:100px;height:60px;
border:1px solid black;
color:block; // トグル対象CSS
background:pink; // トグル対象CSS
line-height:60px;
text-align:center;
cursor:pointer;
}
.box_red {color:white;background:red;}
</style>
<script>
$(function(){
$('.box').click(function(){
$(this).toggleClass( 'box_red' );
})
});
</script>
■12行目のbox_redクラスを17行目で付けたり外したりする事によりアニメーションを実行しています。
メモ
.toggleClassは、クラスを追加したり外す物です。
よって、クラス名は[.]なしです。
〇:'box_red'
✖:'.box_red'
2.図形を変更する
| 下記のスイッチを操作して下さい。スイッチがスライドします。
Warning: include_once(/sample/javascript/animation/toggleClass/switch): Failed to open stream: No such file or directory in /volume1/web/school/wp-content/themes/my_template/functions.php on line 44 Warning: include_once(): Failed opening '/sample/javascript/animation/toggleClass/switch' for inclusion (include_path='.:/usr/share/pear') in /volume1/web/school/wp-content/themes/my_template/functions.php on line 44 |
上記は下記のプログラムで構成されています。
<div class='switch-box'>
<div class='switch'></div>
</div>
<style>
.switch-box{
position:relative;
width:120px;height:60px;
border-radius:60px;
background-color:darkgray;
cursor: pointer;
}
.switch{
position: absolute;
left:5px;top:5px; // トグル対象CSS
width:50px;height:50px;
border-radius:50px;
background-color:tomato;
}
.switch-on{left:65px;top:5px;}
</style>
<script>
$(function(){
$('.switch-box').click(function(){
$('.switch').toggleClass('switch-on',500 );
})
});
</script>
■19行目のswitch-onクラスを24行目で付けたり外したりする事によりアニメーションを実行しています。
■トグルの実行時間は0.5秒です。