bata's log

フロントエンド系のTipsとかメモ

画像ロールオーバーをオブジェクト指向的な書き方で実装すると…

大昔のこの記事のURL元がなくなってて、どんなコードだったのか興味があったので書いてみた。

cl.pocari.org - ロールオーバーのオブジェクト指向的実装

まあこの時代なので「<img onMouseOver=''>とかでやってて、それをJSのみで実装して使いやすくしよう」、みたいな内容だったらしいけど、元記事がないのでその辺はわかりません。

書いてみると普通10行以内のものがこれだけ長くなってしまったけど、ある程度の汎用性と拡張性は確保できてると思います。
まあオブジェクト指向かどうかと言われると違う気がする…

JavaScript

function ImgRollover(el,suffix){
    this.el = '.' + el || '.imgOver';
    this.suffix = suffix || '_o';
    this.event();
    this.preload();
}

ImgRollover.prototype = {

    //イベント
    event: function(){
        var that = this;
        $(that.el).on({
            mouseover: function(){
                $(this).attr('src', that.getOnSrc(this));
            },
            mouseleave: function(){
                $(this).attr('src', that.getOffSrc(this));
            }
        });
    },

    //プリロード機能
    preload: function(){
        var that = this;
        $(this.el).each(function(){
            $('<img />').attr('src',that.getOnSrc(this,that.suffix));
        });
    },

    //画像パスを取得
    getSrc: function(self){
        return $(self).attr('src');
    },

    //mouseoverの画像パスを取得
    getOnSrc: function(self,suffix){
        return this.getSrc(self).replace(/^(.+)(\.[a-z]+)$/, '$1' + this.suffix + '$2');
    },

    //mouseleaveの画像パスを取得
    getOffSrc: function(self,suffix){
        return this.getSrc(self).replace(this.suffix,'');
    }

}

実行

$(function(){
    new ImgRollover('on','_o'); //('クラス名','接尾語')
})