使用jQuery mouseenter/mouseleave触发Featherlight灯箱出现闪烁问题求助
解决Featherlight灯箱鼠标悬停闪烁问题
你的判断没错,闪烁是因为鼠标从触发元素#theboxa移到灯箱#boxa时,触发了#theboxa的mouseleave事件,导致灯箱关闭;而灯箱关闭后鼠标又回到#theboxa区域,再次触发mouseenter打开灯箱,循环往复就出现了闪烁。
下面提供两种可行的解决思路:
方法一:延迟关闭+灯箱区域监听
通过设置延迟关闭定时器,当鼠标离开触发元素时不立即关闭灯箱,而是等待一小段时间;如果这段时间内鼠标移到灯箱上,就取消关闭操作。只有当鼠标同时离开触发元素和灯箱时,才关闭灯箱。
$(document).ready(function() { let closeTimer; const triggerEl = $('#theboxa'); const lightboxContent = $('#boxa'); // 鼠标进入触发元素:打开灯箱并清除关闭定时器 triggerEl.mouseenter(function() { clearTimeout(closeTimer); $.featherlight(lightboxContent, {}); // 给打开后的灯箱容器添加鼠标监听(Featherlight的容器类是.featherlight) $('.featherlight').mouseenter(function() { clearTimeout(closeTimer); }); $('.featherlight').mouseleave(function() { closeTimer = setTimeout(() => { $.featherlight.close(); }, 200); }); }); // 鼠标离开触发元素:设置延迟关闭 triggerEl.mouseleave(function() { closeTimer = setTimeout(() => { $.featherlight.close(); }, 200); }); });
方法二:统一监听鼠标位置
监听全局的mouseover事件,判断鼠标是否在触发元素或灯箱范围内,只有当鼠标不在这两个区域时才关闭灯箱。
$(document).ready(function() { const triggerEl = $('#theboxa'); let lightboxOpen = false; triggerEl.mouseenter(function() { $.featherlight('#boxa', {}); lightboxOpen = true; }); $(document).on('mouseover', function(e) { const isOverTrigger = $(e.target).closest(triggerEl).length > 0; const isOverLightbox = $(e.target).closest('.featherlight').length > 0; if (lightboxOpen && !isOverTrigger && !isOverLightbox) { $.featherlight.close(); lightboxOpen = false; } }); });
注意:第一种方法里的延迟时间(200ms)可以根据实际需求调整,确保鼠标有足够时间从触发元素移到灯箱上。
内容的提问来源于stack exchange,提问作者whywhywhy
相关产品推荐
相关产品推荐

