Jquery .hover -闪烁图像

Jquery .hover - flickering image

本文关键字:图像 闪烁 hover Jquery      更新时间:2023-09-26

我在jQuery中为以下测试页面设置了一个。hover()函数:

正如你将看到的,当你把鼠标移到产品图像上时,我想要出现的叠加会闪烁。有什么想法吗?我能做些什么来解决这个问题?它是否与我应用于图像的jQuery周期插件有关?

$("#productImage_1").hover(
    function() {
        $('#product_1').show();
    },
    function() {
        $('#product_1').hide();
    }
);

问题很可能是,一旦覆盖出现,您不再悬停#productImage_1。你现在悬停在#product_1。这创建了一个无限循环的出现和消失(闪烁)。

$("#productImage_1, #product_1").hover(function() {
    $('#product_1').show();
}, function() {
    $('#product_1').hide();
});

问题发生是因为.productOverlay被显示在#product_1的顶部,因此mouseleave事件被触发,因此,它再次被隐藏。

有许多方法可以处理这个问题,但最流畅的解决方案之一(需要最少数量的事件侦听器)是检查e.target元素,并查看它是否覆盖。比如:
$("#productImage_1").hover(function(e) {
    $('#product_1').show();
}, function(e) {
    // Prevent execution if it's the overlay that is being targeted
    if (e.target.className == 'productOverlay')
        return;
    // Otherwise, hide!
    $('#product_1').hide();
});

编辑:我鼓励人们尽可能多地使用普通JS;因此,使用className而不是像$(e.target).hasClass()这样做。为什么?性能!随后,随着应用程序变得越来越大,您将不得不关注事件及其执行情况;尤其是鼠标相关的事件。您希望避免事件中的长时间运行代码,因此使用本机解决方案:-)