【jQuery】animate() で素早く上下に動くボックスを作ってみよう
animate() で素早く上下に動くボックスを作る
今回は animate() 関数を使ってクリックすると素早く上下に動くピンク色のボックスを作ります。
<サンプル>
下のピンク色のボックスをクリックすると素早く上下に動きます。
<Htmlソース>
<div> 要素だけのシンプルなソースです。※<div> 要素には "test-box" という ID を付けます。
<div id="test-box"></div>
<jQueryコード>
ひとつ目の animate 関数でピンク色のボックスがトップの位置(現在の位置)から 500px 下に移動し、ふたつ目の animate 関数で、そのボックスがトップの位置(現在の位置)から 0px の位置まで移動します。この2つの animate 関数でピンク色のボックスがブーメランのように戻ってくる動きを作っています。
<script type="text/javascript">
$(function(){ //ページが読み込まれたら実行
$("#test-box").click(function(){ //クリックを検出するリスナーをセット
$("#test-box").animate({top:"500px"}, 300); //0.3秒で500pxの位置に移動
$("#test-box").animate({top:"0px"}, 300); //0.3秒で0pxの位置に移動
});
});
</script>
<CSSソース>
ポイントは poition に relative を設定するところです。※ relative は要素の基準位置を現在の位置に設定します。
<style type="text/css">
<!--
#test-box {
background-color: #F39;
height: 100px;
width: 100px;
position: relative;
}
-->
</style>
END