2013-02-04 112 views
1

我无法使图像交换正常工作。问题在于,放置在下面的标题消失在交换后的图像后面,因为它具有绝对位置。我可以通过将固定高度应用于图像周围的额外div来解决问题 - 但由于这必须在响应式布局中工作,因此高度是可变的。jQuery img swap - 保持宽度和高度

我确定有一个简单的解决方案,但无法弄清楚。

已创建以下jsfiddle &粘贴代码:

HTML:

<div class="container"> 
<img src="http://placehold.it/100x100" class="image_off"> 
<img src="http://placehold.it/100x100/E8117F" class="image_on"> 
<h2>Title</h2> 
</div> 

的jQuery:

//image fade on hover 
$('.image_off').on('mouseenter', function() { 
    $(this).fadeOut(200); 
    $('.image_on').fadeIn(200).css('display', 'block'); 
}); 
$('.image_on').on('mouseleave', function() { 
    $(this).fadeOut(200); 
    $('.image_off').fadeIn(200); 
}); 

任何帮助,不胜感激!

回答

2

您不必fadeOutimage_off元素,作为image_on正在消失在顶部。

如果您希望保留此行为,则可以将不透明度设置为接近透明,然后image_on会在顶部淡入淡出。

+0

谢谢!这最适合在图像之间保持适当的淡入淡出效果。 – vonholmes

1

删除position:absolute;

,并添加callback functionJQuery的,使.fadeIn().fadeOut()执行一前一后。

$('.image_off').on('mouseenter', function() { 
    $(this).fadeOut(200,function(){ 
      $('.image_on').fadeIn(200).css('display', 'block'); 
    }); 

}); 
$('.image_on').on('mouseleave', function() { 
    $(this).fadeOut(200,function(){ 
      $('.image_off').fadeIn(200); 
    }); 

}); 

检查出来:http://jsfiddle.net/AliBassam/GTK8T/

+0

大,这也适用。谢谢。 – vonholmes

0

在情况下,它是任何使用人的,最后jQuery的使用:

//image fade on hover 
$('.image_off').on('mouseenter', function() { 
     $(this).animate({opacity: 0.5}, 200); 
     $('.image_on').fadeIn(200).css('display','block'); 
}); 
$('.image_on').on('mouseleave', function() { 
     $(this).fadeOut(200); 
     $('.image_off').animate({opacity: 1}, 200); 
});