タップしてる間だけクラスを付与する | 恋はいつでも横幅320px

恋はいつでも横幅320px

スマホ向けコーディング
・html5
・css3
・jQuery
初心者向け(むしろ俺用)覚え書きblog

スマホでサイトを作る際、
ボタンを押した際のアクションは「:hover」でokだったりします。

が。

ブラウザバックした際、その「:hover」の効果が残ってしまうのがキズです…。



というわけで。

・ボタンをタップした際にclassを付与
・タップを話した際にclassを除去

というjQueryを実装します。
(これならブラウザバックでもアクションが残ってることはありません)



html




css(6~8行目部分がタップしてる間の挙動です)

.button{
display: block;
background: #888;
border-radius: 4px;
}
.button.active{
box-shadow: 0px 0px 5px #fff;
}


jQuery

$('.button')
.bind('touchstart', function () {
$(this).addClass('active');
})
.bind('touchend', function () {
$(this).removeClass('active');
});


「class="button"」が付与されている要素をタップしている間のみ
「class="active"」が追加付与されます。
タップを離すと「class="active"」が解除されます。



以下余談。



複数の要素にタップ時「class="active"」を付与したい場合
(カンマ区切りで要素を表記)

$('.button, .button2, #banner1, #banner2')
.bind('touchstart', function () {
$(this).addClass('active');
})
.bind('touchend', function () {
$(this).removeClass('active');
});



PCで動作確認をしたいのでマウス挙動も追加する(複数のイベントを設定)
(スペース区切りでイベントを表記)

$('.button, .button2, button3')
.bind('touchstart mousedown', function () {
$(this).addClass('active');
})
.bind('touchend mouseup', function () {
$(this).removeClass('active');
});