在淡入淡出时悬停交换图像

时间:2016-01-22 22:46:34

标签: javascript jquery html css css3

我尝试使用淡入/淡出效果在悬停时换出图像。下面的jQuery运行良好,因为它延迟加载悬停图像。

第一个示例显示白色闪烁,因为原始图像在淡入时会被新图像替换。第二个示例通过设置背景显示所需的淡入淡出效果,但不知何故失去淡出效果。

HTML:

<img class="imageHoverLoad lazy" 
  data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg" 
  data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />

jQuery的:

$('.imageHoverLoad').mouseenter(function() {
   var elem = $(this);
   elem.attr('src', elem.attr('data-hover')).hide().fadeIn(400);
});

$('.imageHoverLoad').mouseleave(function() {
   var elem = $(this);
   elem.attr('src', elem.attr('data-original')).hide().fadeIn(400);
});

Codepen:

http://codepen.io/anon/pen/KVQavM

1 个答案:

答案 0 :(得分:3)

您在转换前更换了src,因此没有时间淡出。您需要指定fadeOut并等待动画承诺解决,然后继续:

&#13;
&#13;
$(function() {
  $("img.lazy").lazyload();
});

$('.imageHoverLoad').mouseenter(function() {
  var elem = $(this);
  elem.fadeOut(400).promise().done(function() {
    elem.attr('src', elem.attr('data-hover')).fadeIn(400);
  });
});

$('.imageHoverLoad').mouseleave(function() {
  var elem = $(this);
  elem.fadeOut(400).promise().done(function() {
    elem.attr('src', elem.attr('data-original')).fadeIn(400);
  });
});
&#13;
.swap-image {
  width: 300px;
  height: 300px;
  margin-bottom: 100px;
}
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.js"></script>

<div class="swap-image">
  <img class="imageHoverLoad lazy" data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg" data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />
</div>

<div class="swap-image" style="background: url(http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg) no-repeat;">
  <img class="imageHoverLoad lazy" data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg" data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />
</div>
&#13;
&#13;
&#13;