简体   繁体   English

纯javascript单击div外部时如何关闭菜单?

[英]How to close the menu when clicking outside the div with pure javascript?

I managed to make the function to open the menu when clicking on the button, but I'm having some difficulty closing the menu when clicking outside it, I looked for something about it before coming here, so I ask for everyone's understanding.我设法使 function 在单击按钮时打开菜单,但是在单击外部菜单时关闭菜单时遇到一些困难,我在来这里之前查找了一些相关信息,因此请大家理解。

By clicking on the menu通过点击菜单

在此处输入图像描述

It opens normally正常打开

在此处输入图像描述

I'm trying to create a function so that when the user clicks outside the div, the menu closes by itself我正在尝试创建一个 function 以便当用户在 div 外部单击时,菜单会自行关闭

This is my menu's html code这是我菜单的 html 代码

<div id="main-menu-btn" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<a href="<?= base_url() ?>user/home">Home</a>
<a href="<?= base_url() ?>user/meus_imoveis">Meus imóveis</a>
<a href="<?= base_url() ?>user/meus_clientes">Meus clientes</a>
<hr>
<a href="<?= base_url() ?>user/profile">Meu perfil</a>
<a href="<?= base_url() ?>user/users">Meus usuários</a>
<a href="<?= base_url() ?>user/faturas">Minhas faturas</a>
<hr>
<a href="#" data-toggle="modal" data-target="#modalMaterial">Materiais</a>
<a href="#" data-toggle="modal" data-target="#modalSupport">Suporte</a>
<hr>
<a href="<?= base_url('auth/logout'); ?>">Sair</a>

And this is my javascript code这是我的 javascript 代码

function openNav() {
  document.getElementById("main-menu-btn").style.width = "250px";
}

function closeNav() {
  document.getElementById("main-home").style.width = "0";
}

please add below javascript code请在下面添加javascript代码

 const box = document.querySelector(".sidenav")
// Detect all clicks on the document
document.addEventListener("click", function(event) {
  // If user clicks inside the element, do nothing
  if (event.target.closest(".sidenav")) return
  // If user clicks outside the element, hide it!
   document.getElementById("main-menu-btn").style.width = "0";
})

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

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