【问题标题】:jQuery Image rollover changes all images on the pagejQuery Image rollover 改变页面上的所有图像
【发布时间】:2017-05-04 14:42:09
【问题描述】:

我正在尝试使用悬停时的替代图像来更改图像。我有第二张图片作为 HTML 属性,只想用 jQuery 交换它们,但不知何故,当我将鼠标悬停在一张图片上时,所有产品图片都被当前的替代图片更改。

我的HTML结构如下:

<div class="product-tile">
    <div class="product-image">
        <a class="thumb-link" href="#">
            <img src="images/currentImage" data-alternative-img="images/altImg" />
        </a>
    </div>
</div>

这里是 jQuery 代码:

$('.tiles-container .product-tile').each(function() {
    var $this = $(this).find('.thumb-link img');

    if ($this.data().alternativeImg) {
        var img = $this.attr('src');
        var altImg = $this.attr('data-alternative-img');

        $this.on({
            mouseenter: function() {
                $this.attr('src', altImg);
                $this.attr('data-alternative-img', img);
            },
            mouseleave: function() {
                $this.attr('src', img);
                $this.attr('data-alternative-img', altImg);
            }
        });
    }
});

我已经在控制台中使用了这段代码,并且图像被正确拍摄,if 语句也在正常工作,并且两个属性(src 和 data-alternative-img)都具有正确的值。更改属性可能有问题,我现在两天都想不通,因为图像到处都在被替换,所以任何指向正确方向的人都会非常感激。

【问题讨论】:

  • 为什么需要循环遍历它?您可以选择一个通用选择器并附加事件处理程序,然后使用this 定位当前元素。
  • 这是我最初尝试的,但行为是相同的,我认为我应该循环遍历每个元素以便更具体地捕获它们。但是没有运气
  • 使用mouseovermouseout作为悬停事件,也可以使用.attr('data-alternative-img')代替.data('alternative-img')
  • 谢谢,以后肯定会有一些关于这些差异的内容,但仍然不能解决现有问题。
  • 您为所有悬停图像获得的图像是最后一张吗?

标签: jquery html


【解决方案1】:

你可以直接写mouseenter/mouseleave函数来代替.each函数

<div class="product-tile">
    <div class="product-image">
        <a class="thumb-link" href="#">
            <img src="images/currentImage" data-mouseenter-img="images/altImg" data-mouseout-img="images/currentImage" />
        </a>
    </div>
</div>

$('.product-tile').on({
    mouseenter: function() {
        var $this = $(this).find('.thumb-link img');
        if($this.data().mouseenter-img) {
            $this.attr('src', $this.data('mouseenter-img'));
        }
    }, 
    mouseleave: function() {
        var $this = $(this).find('.thumb-link img');
        if($this.data().mouseout-img) {
            $this.attr('src', $this.data('mouseout-img'));
        }   
    }
});

【讨论】:

  • 如果这段代码不在每个循环中,$(this) 指的是什么?
  • 是的,$(this) 将引用窗口,因为它不会绑定到任何东西。
  • 您能否解释一下为什么我们需要一个 data-mouseout-img,因为它与 src 相同并且它们都是我代码中的缓存变量?
  • 如果您使用mouseout-img,则无需每次设置设置两个变量(img,altImg)。
  • 像魅力一样工作,感谢额外的优化。干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 2015-02-04
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
相关资源
最近更新 更多