繁体   English   中英

jQuery .hover-闪烁的图像

[英]Jquery .hover - flickering image

我在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 ,因此触发了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() 为什么? 性能! 稍后,随着您的应用程序变得越来越大,您将必须注意事件及其执行情况。 特别是与鼠标有关的事件。 您想避免事件中长时间运行的代码,因此采用本机解决方案:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM