
文字や背景の色を変化させる jQueryプラグイン jQuery Color
jQueryの animateメソッドを使用すると様々なアニメーションを演出できますが、要素の背景色やテキストの色などを変更するための CSSプロパティは使用できません。jQuery Colorはそれを可能にするプラグインです。
jQuery Colorの使い方
jQuery Colorプラグインを使う事により CSSのプロパティを animateメソッドに対応させ、さらに多くのアニメーションができるようになります。
HTML head
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.color.js"></script>
HTMLの head要素内に jQueryのライブラリと Color Animationプラグインを読み込ませます。
JavaScript
$(function(){ var $target = $('.target');//対象の要素 var bgColor = '#FF138D';//対象の要素に指定する色 var speed = 5000;//アニメーションのスピード var easing = 'linear';//アニメーションのイージング $target.stop().animate({ backgroundColor: bgColor }, speed, easing); });
色の指定は一部の色名、16進数、RGB、RGBA、HSL、HSLAなどを指定できます。指定できるプロパティは次の通りになります。記述の方法は CSSとは違いローワーキャメルケースになります。
デモ jQuery Colorプラグインを使って背景色を変える 1
jQuery Colorプラグインと、animateメソッドを使い div要素マウスオーバー時に背景色を黒からマゼンタに変更、マウスアウト時にマゼンタから黒に戻します。
HTML body
<div id="demo_1"> <div class="ca"><a href="https://github.com/jquery/jquery-color/" target="_blank">Color animation jQuery-plugin</a></div> </div>
CSS
#demo_1 .ca { background: #000; cursor: pointer; font-weight: bold; line-height: 1; padding: 15px 0; text-align: center; width: 400px; } #demo_1 .ca a { color: #fff; text-decoration: none; }
JavaScript
$(function(){ var $target = $('#demo_1').find('.ca');//対象の要素 var bgColor = $target.css('background-color');//対象になる要素のデフォルトの背景色を取得 var hoverColor = '#FF138D';//対象の要素にマウスオーバーした時の背景色の指定 var speed = 'normal';//アニメーションのスピード var easing ='linear';//アニメーションのイージング $target.hover(function(){//マウスオーバー $(this).stop().animate({ backgroundColor: hover_color//マウスオーバー時に対象になる要素の背景色を変更する }, speed, easing); }, function(){//マウスアウト $(this).stop().animate({ backgroundColor: target_bg_color//マウスアウト時に対象になる要素のデフォルトの背景色を適用する }, speed, easing); }); });
デモ jQuery Colorプラグインを使って背景色を変える 2
jQuery Colorプラグインと、animateメソッドを使い背景色を5秒間隔でランダムに変化させます。
HTML
<div id="demo_2"> <div class="ca"></div> </div>
CSS
#demo_2 .ca { background: #000; height: 400px; }
JavaScript
$(function(){ add_hue(); function add_hue(){ var $target = $('#demo_2').find('.ca'); var speed = 5000; var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; $target.animate({ backgroundColor: hue }, speed, function(){ add_hue(); }); } });