jQueryでボタン作り
アニメーションをつかう
「jQuery最高の教科書」を読んで作りました。
作ってみたボタン
- 通常時
- マウスオーバー時(ふわっと画像が変化します)
HTMLのコード(ボタン部分)
<div class="page-main" role="main"> <div id="button"> <div class="inner"> <button> <span> <img src="kabuki1.png"> <img src="kabuki_green.png"> </span> </button> </div> </div> </div>
- 全体を#buttonで囲んで二つの画像を重ねる。
- imgタグで指定しているkabuki1.pngは通常時に表示する画像、kabuki_green.pngはマウスオーバー時に表示する画像。
- この二つの画像はJava ScriptからCSSの'opacity(不透明度)'を操作する事で切り替えます。
CSSのコード(ボタン部分)
#button button img:first-child { position: absolute; } #button button img:nth-child(2) { opacity: 0; }
- ここのコードは初期状態なので、通常時の画像を絶対配置にし、マウスオーバー時は非表示にします。
- buttonタグの最初の子要素にあたる"kabuki1.png"に対してimg:first-childを指定することで、特定の要素(この場合"kabuki1.png")を対象にスタイルを適用させることができます。
- :first-childは:nth-child(1)を指定した時と同じ動作。
- :nth-child(2)を指定するとbuttonタグの2番目の要素にスタイルを適用させることができます。
Java Scriptのコード(ボタンの部分)
$(function() { var duration = 300; $('#button button') .on('mouseover', function(){ var $btn = $(this).stop(true).animate({ backgroundColor: '#5fb751' //ボタンの背景を緑に }, duration); $btn.find('img:first-child').stop(true).animate({opacity: 0}, duration); $btn.find('img:nth-child(2)').stop(true).animate({opacity: 1}, duration); }) .on('mouseout', function(){ var $btn = $(this).stop(true).animate({ backgroundColor: '#fff' }, duration); $btn.find('img:first-child').stop(true).animate({opacity: 1}, duration); $btn.find('img:nth-child(2)').stop(true).animate({opacity: 0}, duration); }) });
- durationはアニメーションにかける時間を指定しています。
- buttonそれぞれにopacityを指定して画像を切り替えます。
ボタンがふわっと変化するようなアニメーションを作るにはjQuery UIもインポートする。
参考書籍
jQuery最高の教科書 | 株式会社シフトブレイン著