Skip to content

Instantly share code, notes, and snippets.

@hokaccha
Created July 17, 2009 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hokaccha/149052 to your computer and use it in GitHub Desktop.
Save hokaccha/149052 to your computer and use it in GitHub Desktop.
var Rollover = function(elem, suffix) {
// 初期化する
this.namespace = "Rollover"; // 名前空間
this.elem = elem; // ロールオーバーしたい要素
this.suffix = suffix || "_o"; // 接尾語
this.baseSrc = elem.getAttribute("src"); // 元画像のパス
this.overSrc = this.baseSrc.replace(/\.\w+$/, this.suffix + "$&"); // ロールオーバー後の画像
this.addEvent();
this.preLoad();
};
Rollover.prototype = {
// マウスオーバーで画像切り替える
changeToOver: function() {
this.elem.src = this.overSrc;
},
// マウスアウトで画像切り替える
changeToNormal: function() {
this.elem.src = this.baseSrc;
},
// イベントを付加する
addEvent: function() {
var self = this;
$(this.elem)
.bind("mouseover." + this.namespace, function() { self.changeToOver();})
.bind("mouseout." + this.namespace, function() { self.changeToNormal() })
;
},
// イベントを削除する
removeEvent: function() {
$(this.elem)
.unbind("mouseover." + this.namespace)
.unbind("mouseout." + this.namespace)
;
},
// プリロードする
preLoad: function() {
var img = new Image();
img.src = this.overSrc;
}
};
// 実行
$(function() {
var elem = document.getElementById("rollover");
var rollover = new Rollover(elem, "_over");
// イベント削除したり
rollover.removeEvent();
// 再度つけたりできるよ。
rollover.addEvent();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment