jQuery を使用して、ホバー時に src 属性を変更したいと考えています。たとえば、次の HTML があります。
<img src="convert.php?image=images/example.jpg" alt="#" />
ホバーすると、「convert.php?」を削除したいです。HTML が次のようになる文字列:
<img src="image=images/example.jpg" alt="#" />
シンプルでなければなりませんか?
jQuery を使用して、ホバー時に src 属性を変更したいと考えています。たとえば、次の HTML があります。
<img src="convert.php?image=images/example.jpg" alt="#" />
ホバーすると、「convert.php?」を削除したいです。HTML が次のようになる文字列:
<img src="image=images/example.jpg" alt="#" />
シンプルでなければなりませんか?
自分の質問に答えました。このスニペットを見つけました。
$('.item img').each(function(e){
var src = $(this).attr('src');
$(this).hover(function(){
$(this).attr('src', src.replace('convert.php?image=', ''));
}, function(){
$(this).attr('src', src);
});
});
使えるattr(function(){}
mouseleave
以下は同様にイメージを復元します
$(".item img").hover(function () {
var convert='convert.php?image=';
$(this).attr('src',function(idx, attr){
return attr.indexOf(convert) <0 ? convert+attr : attr.replace(convert,'');
});
});
hover の引数として 1 つの関数のみが渡された場合、mouseenter
とmouseleave
イベントの両方に対して実行されます。
$("img").hover(
function () {
var src = $(this).attr('src');
jQuery.data(this, 'old_source', src);
srcNew = src.replace("convert.php?", "");
$(this).attr('src', srcNew);
$(this)., srcNew);
},
function () {
var src = $(this).data('old_source');
$(this).attr('src', src);
}
);