2

我正在寻找一种简单的方法来在悬停时使用交叉淡入淡出交换图像。我见过很多解决方案——但我发现的一切似乎都臃肿而复杂。有没有一种简单的方法可以实现这一目标?

我正在使用的 Img 交换代码:

$(function() {
$(".img-swap").hover(
    function() {
        this.src = this.src.replace("_off","_on");
    },
        function() {
            this.src = this.src.replace("_on","_off");
    });
});

有没有办法在这里添加淡入/淡出?或者这是错误的方法吗?我尝试过的一切似乎都不起作用!任何帮助将不胜感激。

4

3 回答 3

2

jsBin 演示

  $(".img-swap").on('mouseenter mouseleave', function( e ){

    var mE = e.type=='mouseenter';
    var c = ['_on','_off'];
    this.src = this.src.replace( mE?c[1]:c[0] , mE?c[0]:c[1] );
    $(this).hide().stop().fadeTo(1000,1);

  });
于 2012-12-21T10:59:54.427 回答
2

要交叉淡入淡出两个图像,两个图像都会在某个时候可见,因此您需要 DOM 中的两个图像。你可以只用一张图像来做,但是你必须淡出图像,交换源,然后淡入,这不是真正的交叉淡入淡出。

<img src="image1.png" id="test" />
<img src="image2.png" id="test2" />​

JS:

$('#test').on('mouseenter', function() {
        $(this).fadeOut('slow');
        $('#test2').fadeIn('slow');
});

$('#test2').css({left: $('#test').position().left, top: $('#test').position().top})
           .on('mouseleave', function() {
        $(this).fadeOut('slow');
        $('#test').fadeIn('slow');
});
​

小提琴

于 2012-12-21T11:38:54.900 回答
0

使用下面的代码,还包括 jquery。

 $("#one").hover(function(){$('#one').fadeOut(1000);$('#two').fadeIn(2000);}
);
 $('#one').fadeIn(2000);

<span id="one"><img serc="image1path"></span>
<span id="two" style="display:none"><img serc="image2path"></span>
于 2012-12-21T11:01:21.160 回答