我有以下 jQuery 事件绑定(bind)。请参阅下图以查看 DOM。将鼠标悬停在 .gift-price
、.gift-vendor
和 .gift-name
上时,悬停回调会正常运行。但是,当鼠标悬停在图像 (.gift-photo
) 上时,mouseenter
和 mouseleave
回调会在每次鼠标移动时调用。为什么会这样?
$('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/