简体   繁体   English

在div以外的任何地方单击时关闭div

[英]closing a div while click anywhere outside that div

I am trying to create a jquery navigation bar. 我正在尝试创建一个jquery导航栏。 So when I click on div main, a new div will slide down and I want to add an option to close the window if we click anywhere outside the newly opened window. 因此,当我单击div main时,新的div将向下滑动,如果我们单击新打开的窗口之外的任何位置,我想添加一个选项来关闭窗口。 This is the code that I have used but it is not working. 这是我使用过的代码,但是没有用。

The newly opened div doesn't close when I click anywhere outside it. 当我单击新打开的div外部的任何地方时,它都不会关闭。

var $s = $("#main");    
$(document).ready(function () 
{
  $(document.body).click(function()
  {
   $('ul.the_menu').slideToggle('medium');
   if (!$s.has(this).length) 
   {
      $s.hide();
   }    
 });
});

Do you mean something like: 您的意思是:


if(!$(event.target).is('#main')) {
   // your code to close the div
}

You can do this by attaching an event to the "body" of the page is the simplest approach. 您可以通过将事件附加到页面的“正文”来完成此操作,这是最简单的方法。

    $("body").click(function () {
        ....
    });

You are trying to use a javascript dom reference, where you need to use a jquery selector to apply jquery events. 您正在尝试使用javascript dom引用,在该引用中需要使用jquery选择器来应用jquery事件。

I see this question asked at least once a week. 我看到这个问题至少每周问一次。 I usually get away with this but it depends on your logic and markup. 我通常会避免这种情况,但这取决于您的逻辑和标记。

$menu.focusout(function(){ 
    $(this).slideUp(); 
})
var $_theDiv = $('#the_div')

$_theDiv.click(function(e){
    e.stopPropagation();
} );
// stops the event from bubbling up to the body.

$(document).click(function(){ $_theDiv.hide(); });
//Now any time a click event bubbles to the top of the document, you know it wasn't #theDiv

I'm going to go with a basic example to get to the general idea. 我将通过一个基本的例子来了解总体思路。 We show #theDiv. 我们显示#theDiv。 Now we want it to disappear if we click anywhere but on #theDiv. 现在,如果我们单击除#theDiv以外的任何位置,我们希望它消失。 So we use stopPropagation on the event object. 因此,我们在事件对象上使用stopPropagation。 Normally when you click, the click also goes up the parent, and the parent of that parent, and keeps going until you hit the document. 通常,当您单击时,单击也会上升到父级以及该父级的父级,并且一直持续到您单击文档为止。 This is called "event bubbling." 这称为“事件冒泡”。 Since we stopped the bubbling, we know if a click reaches the document (the HTML tag), that it couldn't have come from #theDiv because e.stopPropagation, prevented it. 由于我们停止了冒泡,因此我们知道是否有点击到达文档(HTML标记),因为e.stopPropagation阻止了它,所以它不可能来自#theDiv。 Bubbling is very useful, so only use stopPropagation on elements that have no children (aren't containers). 冒泡非常有用,因此请仅对没有子元素(没有容器)的元素使用stopPropagation。 Things like links and images and buttons. 诸如链接,图像和按钮之类的东西。

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

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