【问题标题】:How to fade "this.src.replace" when swapping images on hover (jQuery) [duplicate]在悬停时交换图像时如何淡化“this.src.replace”(jQuery)[重复]
【发布时间】:2012-07-17 09:59:32
【问题描述】:

可能重复:
jQuery fade to new image

我有以下代码在悬停时交换(预加载)图像:

$(document).ready(function() { 
$(".pf-item img").hover(
      function(){this.src = this.src.replace(".jpg","-h.jpg");},
      function(){this.src = this.src.replace("-h.jpg",".jpg");
 });
 var imgSwap = [];
 $(".img-swap").each(function(){
    imgUrl = this.src.replace(".jpg","-h.jpg");
    imgSwap.push(imgUrl);
});
$(imgSwap).preload();
});
$.fn.preload = function() {
this.each(function(){
    $('<img/>')[0].src = this;
});
}

效果很好,但是我希望能够在图像 .jpg 和 -h.jpg 之间淡入淡出。

有谁知道如何做到这一点/有更好的方法来解决这个问题?我尝试了很多不同的 fadeIn() 方法,但似乎都不起作用,或者只工作了几次,然后替换一个空白图像。

【问题讨论】:

标签: javascript jquery image


【解决方案1】:

我建议使用 mouseover/mouseout 方法。

我的 HTML 是这样设置的。

<div class="imageWrap">
    <img class="shown" src="image-1.jpg" width="300" height="300" />
    <img class="hidden" src="image-2.jpg" width="300" height="300" />
</div>

然后使用 jQuery 你可以像这样在它们之间进行交换

$(".imageWrap").mouseover(function() {
    $(this).children(".shown").fadeOut("fast");
    $(this).children(".hidden").fadeIn("fast");
});

$(".imageWrap").mouseout(function() {
    $(this).children(".shown").fadeIn("fast");
    $(this).children(".hidden").fadeOut("fast");
});

别忘了你的 CSS

.imageWrap {width:300px; height:300px;}
.imageWrap > img {position:absolute;}
.imageWrap > .hidden {display:none;}

【讨论】:

    猜你喜欢
    • 2010-10-24
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多