JavaScript - 如果用户选择另一个菜单项或单击菜单外部,则关闭子菜单

时间:2016-12-17 19:02:29

标签: javascript menu

如果用户选择其他菜单或点击菜单外部(点击页面上的其他内容),我正在尝试弄清楚如何关闭子菜单下拉菜单。我已经阅读并尝试了几种不同的方法,但没有得到任何结论。我只是把自己弄糊涂了什么是最好的或正确的方法。仅使用常规JavaScript - 尝试学习。

HTML

  <div class="container">
<div class="inner-wrap">
    <ul id="filters">
        <li><a href="#" class="filterBtn">one</a>
            <ul class="dropM">
                <li>I belong to one</li>
            </ul>
        </li>
        <li><a href="#" class="filterBtn">two</a>
            <ul class="dropM">
                <li>I belong to two</li>
            </ul>           
        </li>
        <li><a href="#" class="filterBtn">three</a>
            <ul class="dropM">
                <li>I belong to three</li>
            </ul>
        </li>
        <li><a href="#" class="filterBtn">four</a>
            <ul class="dropM">
                <li>I belong to four</li>
            </ul>           
        </li>
    </ul>
</div>

CSS

    html {
  box-sizing: border-box;
  background:#ffc600;
  font-family:'helvetica neue';
  font-size: 20px;
  font-weight: bold;
}
body {
  margin: 0 auto;
  padding: 50px 0;
}
*, *:before, *:after {
  box-sizing: inherit;
}
div.container {padding: 10px; background: #bada55; text-align: center;}
div.inner-wrap {margin: 0 auto; position: relative; display: inline-block;} 

ul#filters { list-style: none;}
ul#filters li {display: inline-block; position: relative;}
ul#filters li > ul.dropM {list-style: none; position: absolute; top: 30px; left: -40px; padding: 15px; border: 1px solid #ccc; background: #fff; display: block; min-width: 200px; display: none; z-index: 201;}
ul#filters li > ul.dropM.open {display: block;}
ul#filters {display: inline-block;}
ul#filters li a.filterBtn {text-decoration: none; padding: 10px 20px; background: #ccc; color: black;}

JS

    const filterMenuBtn = document.querySelectorAll('a.filterBtn');
const dropMenu = document.querySelectorAll('ul.dropM');

function openDropMenu(e){
    filterMenuBtn.forEach(cliks => {
      //console.log(cliks);
      if(cliks === this) {
        this.nextElementSibling.classList.toggle('open');
        //console.log('i clicked this one');
      }
    });
}

filterMenuBtn.forEach(cliks => cliks.addEventListener('click', openDropMenu));

JSFiddle

1 个答案:

答案 0 :(得分:0)

将您的javascript更新为此

const filterMenuBtn = document.querySelectorAll('a.filterBtn');
const dropMenu = document.querySelectorAll('ul.dropM');

function openDropMenu(e) {
if (e.type == 'click'){
    e.currentTarget.nextElementSibling.classList.toggle('open');
} else {
    e.currentTarget.nextElementSibling.classList.remove('open');
}
}

filterMenuBtn.forEach(cliks => cliks.addEventListener('click', openDropMenu));
filterMenuBtn.forEach(cliks => cliks.addEventListener('blur', openDropMenu));