jQueryのアニメーション
jQueryのアニメーション効果
HTML要素のサイズや位置、透明度を時間の経過とともに徐々に変化させ、動いているように見せる。
非表示状態の要素を表示する show()
$( セレクタ ).show( スピード );
スピード:slow, fast または ミリ秒(1000=1秒)
スピードの指定を省略するとアニメーション効果はなく即座に表示する。
使用例
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>jQueryのアニメーション</title>
<style>
div {
width: 200px;
height: 200px;
background-color: red;
display: none;
}
</style>
<script src="../js/jquery-2.2.4.min.js"></script>
<script>
$(function(){
$('button').on('click',function(){
$('div').show('slow');
});
});
</script>
</head>
<body>
<button>表示</button>
<div></div>
</body>
</html>
アニメーション実行前
アニメーション実行後
コールバック関数
<title>jQueryのアニメーション</title>
<style>
div {
width: 200px;
height: 200px;
background-color: red;
display: none;
}
</style>
<script src="../js/jquery-2.2.4.min.js"></script>
<script>
$(function(){
$('button').on('click',function(){
$('div').show('slow',function(){//コールバック関数
//コールバック関数とは処理が終わったら呼び出される関数のこと
$(this).css('background','blue');
});
});
});
</script>
</head>
<body>
<button>表示</button>
<div></div>
</body>
アニメーション実行前
アニメーション実行後
表示中の要素を非表示にする hide()
$( セレクタ― ).hide( スピード, コールバック関数 );
<title>jQueryのアニメーション</title>
<style>
div {
width: 200px;
height: 200px;
background-color: red;
display: none;
}
</style>
<script src="../js/jquery-2.2.4.min.js"></script>
<script>
$(function(){
$('button#show').on('click',function(){
$('div').show('slow');
});
$('button#hide').on('click',function(){
$('div').hide('slow');
});
});
</script>
</head>
<body>
<button id="show">表示</button>
<button id="hide">非表示</button>
<div></div>
</body>
アニメーション実行前
show()の実行後
hide()で赤い四角の要素を消す
要素の表示・非表示を交互に切り替える toggle()
$( セレクタ― ).toggle( スピード, コールバック関数 );
<title>jQueryのアニメーション</title>
<style>
div {
width: 200px;
height: 200px;
background-color: red;
display: none;
}
</style>
<script src="../js/jquery-2.2.4.min.js"></script>
<script>
$(function(){
$('button').on('click',function(){
$('div:not(:animated)').toggle('slow');
});
});
</script>
</head>
<body>
<button id="show">表示・非表示</button>
<div></div>
</body>
アニメーション実行前
toggle()を実行して要素を表示する
toggle()を実行して要素を消す