Skip to content

Instantly share code, notes, and snippets.

@hokaccha
Created May 19, 2010 10:51
Show Gist options
  • Save hokaccha/406184 to your computer and use it in GitHub Desktop.
Save hokaccha/406184 to your computer and use it in GitHub Desktop.
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>rollover javascript sample</title>
</head>
<body>
<p class="description">画像以外(テキストとか)にオンマウスしたときにも画像が切り替わるよ。</p>
<p><a class="hoge" href="http://example.com/"><img src="img/test.gif" alt="test">hoge</a></p>
<p><a class="hoge" href="http://example.com/"><img src="img/test.png" alt="test">hoge</a></p>
<p><a class="hoge" href="http://example.com/"><img src="img/test.gif" alt="test"><img src="img/test.png" alt="test">hoge</a></p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="rollover.js"></script>
</body>
</html>
(function() {
var target = 'a.hoge';
var postfix = '_o';
$(target)
.find('img').each(function() {
var src = this.src;
var src_o = src.replace(/(\.[^.]+$)/, postfix + '$1');
(new Image).src = src_o;
$.data(this, 'src', src);
$.data(this, 'src_o', src_o);
})
.end()
.hover(
function() {
$(this).find('img').each(function() {
this.src = $.data(this, 'src_o');
});
},
function() {
$(this).find('img').each(function() {
this.src = $.data(this, 'src');
});
}
);
})();
/* 実装例をもう一個。挙動は同じ。こっちのほうが早いかな? */
(function() {
var target = 'a.hoge';
var postfix = '_o';
var over_regex = new RegExp('(\.[^.]+$)');
var out_regex = new RegExp(postfix + '(\.[^.]+$)');
$(target)
.find('img').each(function() {
(new Image).src = this.src.replace(over_regex, postfix + '$1');
})
.end()
.hover(
function() {
$(this).find('img').each(function() {
this.src = this.src.replace(over_regex, postfix + '$1');
});
},
function() {
$(this).find('img').each(function() {
this.src = this.src.replace(out_regex, '$1');
});
}
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment