gpt4 book ai didi

javascript - jQuery "show/hide div on click"和 "click outside to hide"不能一起工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:34 32 4
gpt4 key购买 nike

//我搜索了但没有运气,所以我开始一个新问题 :)

我有:

<a class="icon hide-text" id="btnNoti5" href="#">Notification</a>

我想要:当我点击这个 a ,它将显示/隐藏一个 div,当我在该 div 外部单击时,如果它可见,它就会隐藏。

我使用这段代码来显示/隐藏。它工作正常:

var divNotifi = $('#divNotifi');
$('#btnNoti5').click(function(e)
{
if (divNotifi.is(":visible"))
{
divNotifi.hide();
}
else
{
divNotifi.show();
}
}

但是当我添加此代码以在用户单击外部时隐藏 div 时,它确实有效,但上面的代码停止工作:第一次单击,它显示 div。第二次点击:没有任何反应。 div 没有按预期隐藏。

$(document).mouseup(function (e)
{
var container = $("#divNotifi");
if (container.has(e.target).length == 0)
{
container.hide();
}
});

请帮帮我。非常感谢。

最佳答案

$(document).on('click', function(e) {
var elem = $(e.target).closest('#btnNoti5'),
box = $(e.target).closest('#divNotifi');

if ( elem.length ) { // the anchor was clicked
e.preventDefault(); // prevent the default action
$('#divNotifi').toggle(); // toggle visibility
}else if (!box.length){ // the document, but not the anchor or the div
$('#divNotifi').hide(); // was clicked, hide it !
}
});

FIDDLE

关于javascript - jQuery "show/hide div on click"和 "click outside to hide"不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16885938/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com