【问题标题】:jquery hover image swap using 2 images in same divjquery悬停图像交换使用同一div中的2个图像
【发布时间】:2014-06-19 21:59:56
【问题描述】:

我正在尝试将 shopify 平台用于小型商业网站。我在我的主要收藏页面上构建了大部分网站,但我希望为项目的正面/背面设置图像悬停效果。目前我的 html 是这样输出的,其中产品列表中的第一项和第二项在 div 中列出。它的工作方式。基本上我想让图像在页面加载时淡入淡出,当悬停在淡出上时,然后淡入 div 中的第二个图像,当悬停叶恢复到原始图像时。

.html

<div class="image">
  <a href="{{ product.url | within: collection }}">
    <img src="{{ product.featured_image.src | product_img_url: 'large' }}" alt="{{ product.featured_image.alt | escape }}"class="img-responsive collectionItem">
    <img src="{{ product.images[1] | product_img_url: 'large' }}" alt="{{ product.title | escape  }}"   class="img-responsive collectionItem" style="display:none"/>
  </a>
</div>

.js

$('.collectionItem').hover(function() {
    $(this).fadeOut();
    $(this).next('img').stop(true, true).fadeIn('slow');
        }, function() {
    $(this).next('img').fadeOut();
    $(this).stop(true, true).fadeIn('slow');
});

【问题讨论】:

  • 旁注:重复 $(this) 选择器是浪费处理。使用局部变量(当最小化时,代码也更短作为奖励)。
  • 计划在我想出正确淡入和淡出而不闪烁的最佳方法后

标签: javascript jquery html css


【解决方案1】:

JSFiddle:http://jsfiddle.net/TrueBlueAussie/49fpX/1/

您需要链接fade outfade in 以避免奇怪的结果。将鼠标悬停在一个元素上通常会更好,因为当悬停元素消失时,一些浏览器会做一些奇怪的事情:

function swapImg($container) {
    var $image = $container.find('img:visible');
    var $image2 = $image.siblings();
    $image.stop().fadeOut(function(){
        $image2.stop().fadeIn();
    });
}
$('.image').hover(function () {
    swapImg($(this));
}, function () {
    swapImg($(this));
});

【讨论】:

  • 制作一个单独的函数是要走的路。这种方式在网站上也非常可重用。非常感谢,我的头撞到了墙上。
猜你喜欢
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多