jquery:隐藏触发器或弹出窗口的 mouseleave 事件上的弹出窗口
我有一个弹出菜单出现在我的页面上的元素的 onclick 事件中,如下所示...
$('.triggerDiv').click(function() {
var pos = $(this).offset();
$('#popupDiv').css({
"left": (pos.left + this.width()) + "px",
"top": pos.top + "px"
}).slideDown();
});
我还有一个 mouseleave 事件附加到弹出窗口以将其隐藏在 mouseleave 上。
$('#popupDiv').mouseleave(function() {
$('#popupDiv').slideUp();
});
我想做的是,如果鼠标也离开触发器,则隐藏弹出窗口。简单的解决方案是 -
$('.triggerDiv').mouseleave(function() {
$('#popupDiv').slideUp();
});
但问题是我在页面上有多个触发元素,它们都显示相同的弹出 onclick。在这种情况下,我如何正确处理 mouseleave 事件以隐藏/显示弹出窗口?
I have a popup menu appearing onclick event of an element on my page like this...
$('.triggerDiv').click(function() {
var pos = $(this).offset();
$('#popupDiv').css({
"left": (pos.left + this.width()) + "px",
"top": pos.top + "px"
}).slideDown();
});
I also have a mouseleave event attached to the popup to hide it on mouseleave.
$('#popupDiv').mouseleave(function() {
$('#popupDiv').slideUp();
});
What I want to do is hide the popup if the mouse leaves the trigger as well. Simple solution would be -
$('.triggerDiv').mouseleave(function() {
$('#popupDiv').slideUp();
});
But the problem is that I have multiple trigger elements on the page that all display the same popup onclick. In this case how can I correctly handle the mouseleave event to hide/show the popup?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要确保弹出窗口仅在用户的鼠标离开弹出窗口和触发器 div 时关闭,请尝试以下代码:
上面的代码使用
setTimeout
函数在关闭弹出窗口之前等待 300 毫秒。这为用户提供了足够的时间将鼠标从触发器 div 移动到弹出窗口,反之亦然。请注意,当用户的鼠标进入弹出窗口时,代码通过使用clearTimeout
取消closeTimer
来防止弹出窗口关闭。根据我的经验,这使得弹出窗口和悬停菜单更易于使用。另外,如果有大量
.triggerDiv
,我会考虑使用 live events 。To ensure that the popup only closes when use's mouse has left both the popup and the trigger-div, try this code:
The code above uses the
setTimeout
function to wait 300 milliseconds before closing the popup. This gives the user enough time to move their mouse from the trigger-div to the popup and vise versa. Note that when the user's mouse enters the popup, the code prevents the popup from closing by usingclearTimeout
to cancel thecloseTimer
. In my experience this makes popups and hover menus much easier to use.Also, if there are large number of
.triggerDiv
s, I'd consider using live events.在函数体中使用 JQuery
$(this)
引用:Use a JQuery
$(this)
reference in the function body: