【问题标题】:jQuery "show/hide div on click" and "click outside to hide" not working togetherjQuery“单击时显示/隐藏 div”和“单击外部隐藏”不能一起工作
【发布时间】:2013-06-03 04:00:41
【问题描述】:

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

我有:

<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();
    }
});

请帮助我。非常感谢。

【问题讨论】:

  • if (divNotifi.is(":visible")) { divNotifi.hide(); } else { divNotifi.show(); } 只需使用:divNotifi.toggle()
  • api.jquery.com/toggle 试试这个
  • @gdoron 和@VJD:谢谢。我知道这个。但是如果我使用toggle(),问题仍然存在:D

标签: javascript jquery


【解决方案1】:
$(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

【讨论】:

  • 谢谢。我会试试这个。嗯....你能解释一下我的代码中问题的原因是什么吗?
  • 第一个点击功能没有正确关闭,第二个功能确实有效,但在点击divNotifi元素时却不行,因为has()检查targetinside divNotifi,因此您必须单击 divNotifi 内的元素,而不是元素本身。
  • 现在一切正常。感谢您的解决方案和解释。
【解决方案2】:

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

$(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;
});

【讨论】:

  • @Hugo Mallet 请问container.has(e.target).length === 0是什么意思,为什么第二次点击事件处理函数需要return false?谢谢。
【解决方案3】:

我喜欢用一个技巧来处理这样的事情。

在 jQuery 库中:

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

无论何时显示 - 添加一个名为“show”的类。

然后检查它是否显示:

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

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

所以我正在做的是:

当显示 - 添加类“显示” 点击 - 检查是否有类“显示”而不是删除类。

希望你能找到使用我的把戏的方法:)

当事情如此生动时,它使做事情变得非常容易。 不太喜欢我的方法 - 但我喜欢,它让你远离混乱。

【讨论】:

    【解决方案4】:
    $("#btnNoti5").click(function(){
        $("#notify").show();
    });
    
    $("#notify").click(function(){
        $("#notify").hide();
    });
    

    【讨论】:

      猜你喜欢
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 2023-03-15
      相关资源
      最近更新 更多