-
Notifications
You must be signed in to change notification settings - Fork 0
imageHover.js
Manabu Yasuda edited this page May 2, 2016
·
4 revisions
-
$imageに処理の対象にする要素を指定 -
onとoffとcurrentに画像ファイル名の末尾につける状態を指定 -
currentがついている場合は処理されない
$(function() {
// @desc - img要素内のsrc属性をマウスオーバーに応じて置換する。プリロードに対応。
function imageHover() {
var $image = $('img');
var on = '_on.';
var off = '_off.';
var current = '_current.';
// ページ内に対象の要素がある場合に処理。
if($image.length) {
$image.each(function() {
var $this = $(this);
// imageオブジェクトを生成して、`on`画像のプリロードをする。
if($this.attr("src").match(off)){
var preloadImage = new Image();
preloadImage.src = $this.attr("src").replace(off, on);
}
// src属性に`off`が入っている場合だけ、
// マウスオーバーで`off`を`on`に
// マウスアウトで`on`を`off`に変更する。
if(!$this.attr('src').match(current) && $this.attr('src').match(off)) {
$this.hover(
function() {
$this.attr('src', $this.attr('src').replace(off, on));
},
function() {
$this.attr('src', $this.attr('src').replace(on, off));
}
);
}
});
}
}
imageHover();
});_off.と一致する場合は_on.に切り替わる。_current.に一致する場合は処理されない。
<img src="example_off.jpg">
<img src="example_current.jpg"">