单击关闭菜单 [英] Close the menu on click

查看:106
本文介绍了单击关闭菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过单击链接或在菜单外单击来关闭菜单.为了保持美观和轻巧,我不想使用jQuery.

I want to close my menu by clicking on a link or when I click outside the menu. In the interest of keeping things nice and light, I don't want to use jQuery.

我该怎么做?

<nav class="nav">
  <div class="nav__left">
    <h3><a href="#home">DenisMasot</a></h3>
  </div>
  <input type="checkbox" /><label class="burger" for="nav"></label>
  <ul  class="nav__right">
    <li class="active">
      <h3><a href="#home">home</a></h3>
    </li>
    <li>
      <h3><a href="#about">À propos</a></h3>
    </li>
    <li>
      <h3><a href="#production">Réalisation</a></h3>
    </li>
    <li>
      <h3><a href="#contact">Contact</a></h3>
    </li>
  </ul>
</nav>

推荐答案

可以使用 addEventListener().然后,您需要逻辑来确定单击目标是否在菜单上或其任何元素中,还是在页面上的其他地方.

It can be done with DOM API using addEventListener() on document. You then need logic to find if the click target was on the menu or any of its elements, or somewhere else on the page.

isDescendent()如何在Javascript中检查一个元素是否包含在另一个元素中

isDescendent() borrowed from How to check in Javascript if one element is contained within another

然后可以使用element.style.display = 'none'

我会质疑不使用jQuery的动机,从长远来看,您将为自己做更多的工作...

I would question motivation to not use jQuery, you'll be making a lot more work for yourself in the long run...

var menu = document.querySelector("nav.nav");
var checkbox = document.querySelector("input[type=checkbox]");

document.addEventListener("click", function(e) {
  if (menu != e.target && 
      ! isDescendant(menu, e.target)) {
    console.log("Clicked somewhere else");
    menu.style.display = 'none';
    checkbox.checked = false;
  }
  
}, false);

function isDescendant(parent, child) {
     var node = child.parentNode;
     while (node != null) {
         if (node == parent) {
             return true;
         }
         node = node.parentNode;
     }
     return false;
}

<div>
  Rest of page...
</div>

<nav class="nav">
    <div class="nav__left">
      <h3><a href="#home">DenisMasot</a></h3>
    </div>
    <input type="checkbox" /><label class="burger" for="nav"></label>
    <ul  class="nav__right">
      <li class="active">
        <h3><a href="#home">home</a></h3>
      </li>
      <li>
        <h3><a href="#about">À propos</a></h3>
      </li>
      <li>
        <h3><a href="#production">Réalisation</a></h3>
      </li>
      <li>
        <h3><a href="#contact">Contact</a></h3>
      </li>
    </ul>
  </nav>

这篇关于单击关闭菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆