繁体   English   中英

jQuery“显示/隐藏div点击”和“点击外面隐藏”不能一起工作

[英]jQuery “show/hide div on click” and “click outside to hide” not working together

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

我有:

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

我想的是:当我点击此a ,它会显示/隐藏一个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 !
    }
});

小提琴

使用相同的事件以阻止其传播

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

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

有一个技巧我喜欢用于这样的事情。

在jQuery库中:

$('#div').addClass('Class-Name');

每当它显示时 - 添加一个名为“show”的类。

而不是检查它是否显示:

if ($('#div').hasClass('Class-Name') )
{
     // some actions
}

.hasClass()也是jQuery库的一部分。 并且jQuery库中的最后一个函数是: .removeClass()

所以我在做的是:

show时 - 在点击时添加类“show” - 检查是否有类“show”而不是删除类。

希望你能找到使用我的技巧:)

当它们如此图形化时,它很容易做到。 不太喜欢我的方法 - 但我这样做,它让你远离混乱。

$("#btnNoti5").click(function(){
    $("#notify").show();
});

$("#notify").click(function(){
    $("#notify").hide();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM