7 月26th

jQueryによるマウスオーバで自動画像切り替え

t-matsuda jQuery Read on

画像をマウスオーバで切り替えたりするとき、通常は
imgタグに


<img src="bt_01.gif" onmouseout="MM_swapImgRestore()"
 onmouseover="MM_swapImage('Image1','','bt_01_over.gif',1)" id="Image1" border="0" />

のように、明示的にonmouseoutのときの処理と、onmouseoverのときの処理を書く必要があります。
※上記は、Dreamweaverで作った場合の例。

これをいちいち、書いていたらめんどくさい。
(Dreamweaverの場合は自動的に書かれるから意識しなくても簡単にかけますが)
そして、ソースがごちゃごちゃして汚くなっちゃう。

それを簡単に解決してくれるのが、jQuery_Autoというプラグイン
これの使い方は、
1.jQueryとjQuery_autoを読み込む


<script src="jquery.js" type="text/javascript"></script>
<script src="jquery_auto.js" type="text/javascript"></script>

2.img タグに class=”Hover”を追加


<img src="bt_01.gif" class="Hover" id="Image1" border="0" height="41" width="174" />

3.マウスオーバ用の画像を「画像名_over.画像拡張子」で準備する
例)今回だと bt_01_over.gif

これだけです。
これだけで、ここにあるみたいな
ロールオーバが出来ます。

すばらしい!さすが、jQuery!素敵です。

ですが、今回はこのjQuery_Autoをちょっとカスタマイズしてみました。
(てか、結構変えたw)

個人的に思った、jQuery_Autoの改善点
・class指定がHoverに依存するのがヤダ
・正直、ロールオーバしか使わない。だけど、他の機能も付いてきちゃう。

ということで、作りました。
jquery_over.js


// jQuery_Auto 0.9
// Automatic functions for webpages (using the wonderful jQuery library)

// Copyright: (c) 2006, Michal Tatarynowicz (tatarynowicz@gmail.com)
// Licenced as Public Domain (http://creativecommons.org/licenses/publicdomain/)
// $Id: jquery_auto.js 426 2006-05-06 19:54:39Z Michał $

// Mouse hover

//
// t-matsuda edit 2007-07-26
// 

$(function(){
	$("img[@ref=over]")
		.mouseover(function () {
			this.src = this.src.replace(/^(.+)(.[a-z]+)$/, "$1_over$2");
		})
		.mouseout(function () {
			this.src = this.src.replace(/^(.+)_over(.[a-z]+)$/, "$1$2");
		})
		.each(function () {
			this.preloaded = new Image;
			this.preloaded.src = this.src.replace(/^(.+)(.[a-z]+)$/, "$1_over$2");
	});
});

1.jQueryとjQuery_autoを読み込む


<script src="jquery.js" type="text/javascript"></script>
<script src="jquery_over.js" type="text/javascript"></script>

2.img タグに ref=”over”を追加


<img src="bt_01.gif" ref="over" id="Image1" border="0" height="41" width="174" />

3.マウスオーバ用の画像を「画像名_over.画像拡張子」で準備する
例)今回だと bt_01_over.gif

実行結果)
http://www.mj-site.net/jQuery/imgOver.html

うん。いいね。
これ使えば、HTMLが汚くなることも無くなって超すっきり!


About this entry