【问题标题】:JQuery Hover Swap Image - Not returning to original imageJQuery Hover Swap Image - 不返回原始图像
【发布时间】:2014-01-23 04:05:30
【问题描述】:

我学习了一些 JQuery 教程并研究了缩略图悬停交换图像功能。最终,我能够将其合并到我的客户网站中并且它正在工作!但是,当我将鼠标悬停时,主图像不会返回到原始图像。

这是我的 JQuery:

function myFunction(){
    jQuery('#thumbs img').hover(function(){
        jQuery('#largeImage').attr('src',jQuery(this).attr('src').replace('thumb','large'));
    });
}

jQuery(document).ready(function(){
    jQuery(myFunction);
});

我的主图像使用 id=largeImage

我的缩略图被包裹在一个 id=thumbs 的 div 中

除了返回原始图像之外,这是可以正常工作的页面: http://test.pillarsoflifebook.com/tables/tabletops/wood/solid-plank-oak/solid-plank-oak/

我似乎无法弄清楚如何合并 .hover 的 mouseout 回调函数。我在想我应该将 largeimg src 设置为一个变量并在 mouseout 函数中替换它。

非常感谢任何建议!谢谢!

【问题讨论】:

  • 我建议您不要使用这种方法。它陈旧且效率低下。而是尝试使用 CSS :hover 选择器、svg 资源和 CSS3 转换。

标签: jquery image swap jquery-hover


【解决方案1】:

试试

function myFunction() {
    var $large = jQuery('#largeImage');

    //store the default image as the data src
    $large.data('src', $large.attr('src'));

    var src = jQuery('#largeImage').attr('src');
    jQuery('#thumbs img').hover(function () {
        $large.attr('src', jQuery(this).attr('src').replace('thumb', 'large'));
    }, function () {
        //on mouse leave put back the original value
        $large.attr('src', $large.data('src'));
    });
}

jQuery(document).ready(function () {
    jQuery(myFunction);
});

另一种方法

function myFunction() {
    var $large = jQuery('#largeImage');
    //you can also use a closure variable, if you don't want to change the default image in the same page you can use this one.
    //but if you want to change the default image using a function it won't work, in the first approach along with the src attribute if you change the data src that will work
    var src = $large.attr('src');
    jQuery('#thumbs img').hover(function () {
        $large.attr('src', jQuery(this).attr('src').replace('thumb', 'large'));
    }, function () {
        $large.attr('src', src);
    });
}

jQuery(document).ready(function () {
    jQuery(myFunction);
});

【讨论】:

  • 我尝试了第一种方法,效果很好!太感谢了!我将逐步完成它,直到我更好地理解它,但现在 - 它是功能性的!
猜你喜欢
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 2013-09-03
相关资源
最近更新 更多