jQueryUIをはじめる方は必見、超簡単サンプル集~その4~
jQueryUIのサンプルスクリプトを作成していきます。
前回はウィジェット編でしたね。今回はエフェクト編です。
・jQuery及びjQueryUIのバージョンは次の通りです。
jQuery :1.9.1
jQueryUI:1.10.3
・そして、今回作成するのは次の4個。
Add/RemoveClass, ColorAnimation, Effect, Hide
早速一つずつサンプルを見ていきましょう。
まずは、Add/RemoveClassのサンプルです。
1.Add/RemoveClassのサンプルスクリプト
スタイルと組み合わせて表示を動的に変化させます。
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
.toggler {width:300px; height:200px;}
.newClass{width:600px; height:400px; font-size:32px; background-color:red;}
</style>
<script>
$(function() {
$( "#button" ).click(function() {
$( "#effect" ).addClass( "newClass", 5000, callback );
return false;
});
function callback() {
setTimeout(function() {
$( "#effect" ).removeClass( "newClass" );
}, 1500 );
}
});
</script>
</head>
<body>
<input type="button" id="button" value="click">
<div class="toggler">
<div id="effect">この領域にクラス「newClass」をaddします</div>
</div>
</body>
</html>
→div要素のサイズを変更していますが、ボタンクリックだけではなく
チェックボックスやラジオボタンの選択アクションなどで
文字などのスタイルを変更するときなどに使えますね。
なお、removeClassを使って自動的に元の表示に戻しています。
次はColorAnimationを実装してみましょう。
2.ColorAnimationのサンプルスクリプト
先ほどのAddClassでも色の変化をつけることができましたが、
こちらでも可能です。
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
.toggler{ width: 500px; height: 200px; }
#effect { width: 240px; height: 200px; }
</style>
<script>
$(function() {
var state = true;
$("#button").click(function() {
if(state){
$("#effect").animate({
backgroundColor: "#aa0000",color: "#fff",width: 500
}, 1000 );
}else{
$("#effect").animate({
backgroundColor: "#fff",color: "#000",width: 240
}, 1000 );
}
state = !state;
});
});
</script>
</head>
<body>
<input type="button" id="button" value="click">
<div class="toggler">
<div id="effect">背景の色が赤と白色で変化します</div>
</div>
</body>
</html>
→こちらも色だけでなくサイズも変えています。
ボタンをトグル形式にしているので、もう一度クリックすると元に戻ります。