javascript - jQuery 的悬停行为问题

标签 javascript jquery css jquery-events

我有以下 jQuery 事件绑定(bind)。请参阅下图以查看 DOM。将鼠标悬停在 .gift-price.gift-vendor.gift-name 上时,悬停回调会正常运行。但是,当鼠标悬停在图像 (.gift-photo) 上时,mouseentermouseleave 回调会在每次鼠标移动时调用。为什么会这样?

$('div.gift-gallery-item').hover(
    function(e) {
        var offset = $(this).offset();
        var itemWidth = $(this).width();
        var itemHeight = $(this).height();
    
        var hoverItem = $('div#gift-gallery-item-hover');
        hoverItem.height(140).width(itemWidth * 2);
        hoverItem.css('left', offset.left).css('top', offset.top);
        hoverItem.show();
                                            
        console.log('in: ' + offset.left +', '+ offset.top);
        console.log(this);
    },
    function(e) {
        $('div#gift-gallery-item-hover').hide();
        console.log('out!');
    } 
)

DOM 引用图片

黄色框是.gift-gallery-item div:

最佳答案

解决了我自己的问题。基本上悬停行为是正确的,但是当绝对定位的悬停信息 div 位于鼠标下方时,mouseleave 事件将在 gift-gallery-item 上触发。简单的解决方案是将悬停拆分为其 mouseenter 和 mouseleave 事件,并使用 one() 而不是 bind() 仅绑定(bind)一次 mouseleave。然后在悬停信息 div 的 mouseleave 事件中,我将 mouseleave 重新绑定(bind)到 gift-gallery-item。

$('div.gift-gallery-item').bind('mouseenter', function(e) {
    var offset = $(this).offset();
    var itemWidth = $(this).width();
    var itemHeight = $(this).height();

    var hoverItem = $('div#gift-gallery-item-hover');
    hoverItem.height(140).width(itemWidth * 2);
    hoverItem.css('left', offset.left).css('top', offset.top);
    hoverItem.show();

    console.log('in: ' + offset.left +', '+ offset.top);
    console.log(this);
});

$('div.gift-gallery-item').one('mouseleave', mouseLeaveEvent);

var mouseLeaveEvent = function() {
    $('div#gift-gallery-item-hover').hide();
    console.log('out!');
};

$('div#gift-gallery-item-hover').hover(
    function(e) {

    },
    function(e) {
        $('div.gift-gallery-item').one('mouseleave', mouseLeaveEvent);
    }
);

关于javascript - jQuery 的悬停行为问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6090463/

相关文章:

javascript - 我正在尝试将一些表单数据从一个 html 页面传递到另一个

css - 禁用环绕 float 图像的文本

javascript - Google Chrome 中的 Canvas 点击区域是否仍然可用?

javascript - 页面重新加载成功时如何隐藏模式弹出窗口

javascript - LinkedIn 登录按钮未显示

jquery:即使在不同的字段集中也选择下一个输入

css - 悬停时获得棕褐色效果图像和全彩色?

Outlook 2013 中的 HTML 电子邮件未对齐?

javascript - jQuery AJAX 自动刷新值

javascript - 如何根据每个 LI.span 中的数字对列表进行排序?