簡體   English   中英

jQuery的懸停行為問題

[英]Hover behaviour issue with jQuery

我有以下jQuery事件綁定。 請參考下圖查看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位於鼠標下方時,將在gift-gallery-item上觸發mouseleave事件。 一種簡單的解決方案是將鼠標懸停在其mouseenter和mouseleave事件中,並使用one()而不是bind()一次mouseleave。 然后,在懸停信息div的mouseleave事件中,我將mouseleave重新綁定在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);
    }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM