简体   繁体   English

在 DIV 外部单击以隐藏它

[英]Click outside of the DIV to hide it

This is a simple example of my HTML page, I have navbar with a dropdown menu display: 'none' , and when I click on <li class="main-ul-li clickToDropDown">Example</li> it display the menu display: 'block' ...这是我的 HTML 页面的一个简单示例,我有一个带有下拉菜单display: 'none' ,当我点击<li class="main-ul-li clickToDropDown">Example</li>时,它会显示菜单display: 'block' ...

Now my question is: How can I hide the menu again when I click outside of it (outside of the li and the div)?现在我的问题是:当我在菜单之外(在 li 和 div 之外)单击时,如何再次隐藏菜单?
My code is 100% vanilla JavaScript我的代码是 100% vanilla JavaScript

And thank you!谢谢!

 const dropdown_function = () => { const dropdown_menu = document.querySelector('.dropdown-menu'); const dropdown_li = document.querySelector('.clickToDropDown'); dropdown_li.addEventListener('click', () => { dropdown_menu.style.display = 'block'; }); } dropdown_function();
 ul { list-style: none; }.main-ul { display: flex; align-items: center; }.main-ul-li { margin:10px 20px; cursor: pointer; }.dropdown-menu { position: absolute; top: 60px; display: none; }
 <!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <header> <nav> <!-- Navbar --> <ul class="main-ul"> <!-- ul --> <li class="main-ul-li clickToDropDown">Example</li> <!-- li --> <div class="dropdown-menu"> <!-- dropdown menu --> <ul> <li>Example1</li> <li>Example2</li> <li>Example3</li> </ul> </div> <li class="main-ul-li">Example</li> <li class="main-ul-li">Example</li> </ul> </nav> </header> </body> </html>

EDIT:编辑:
I've found the solution-我找到了解决方案-

const dropdown_function = () => {
    const dropdown_menu = document.querySelector('.dropdown-menu');
    const dropdown_li = document.querySelector('.clickToDropDown');

    dropdown_li.addEventListener('click', () => {
        dropdown_menu.style.display = 'block';

<!--func added-->
        document.addEventListener('mouseup', function(e) {
          if (!dropdown_menu.contains(e.target)) {
            dropdown_menu.style.display = 'none';
          }
        });
<!--/func added-->

        });
}

You can add something like this:您可以添加如下内容:

document.addEventListener('click', function(event) {
    var isClickInside = dropdown_li.contains(event.target);
    if (isClickInside) {
      //More Stuff
    }
    else {
      dropdown_menu.style.display = 'none';
    }
});

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

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