如何在用户单击时关闭下拉菜单

How to close dropdown menu when user clicks

我正在使用可点击的下拉菜单进行导航。下拉列表使用输入标签。我遇到困难的地方是,如果访问者单击页面上的其他位置,我需要关闭下拉菜单。我正在尝试使用目标 属性、matches() 方法和 onclick 事件。

我在控制台中注意到,当我打开下拉菜单时,两个条件语句都会出现,但下拉菜单不会打开。就好像下拉菜单同时打开和关闭一样。

我哪里做错了,我该如何让它正常运行,以便用户可以简单地打开下拉菜单并在他们单击网页上的其他位置时将其关闭?

提前致谢!下面是代码。这是代码笔:https://codepen.io/bfoley650/pen/NWxeXRB?editors=1111

HTML

<div class="dropdown">
    <input id="checkId" type="checkbox" name="menu" />
    <label for="checkId">
         <span class="heyhey">⋮</span>
    </label> 
    <div class="dropdown-content">
      <ul class="heyheyhey">
      <li><a href="#">Item 1</a></li>
      <li><a href="#">Item 2</a></li>
      <li><a href="#">Item 3</a></li>
        <li><a href="#">Item 4</a></li>
 
      </ul>
    </div>  
</div>

CSS

span {
  color: black;
  font-size: 24px;
  margin: 0 15px;
}

li {
  list-style-type: none;
}

.dropdown {
  float: left;
  overflow: hidden;
  font-size: 17px;
  border: none; 
  outline: none; 
  color: white;
  background-color: inherit;
  font-family: inherit; 
  margin: 10px 0; 
}
 
.dropdown-content {
  display: none;
  position: absolute;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 20px 12px 0;
  text-decoration: none;
  display: block;
  text-align: left;
}

input {
  display: none;
}

label {
  position: relative;
  cursor: pointer;
}


input:checked~.dropdown-content {
  display: block;
}

JS

let el = document.querySelector(".dropdown-content"); 

window.onclick = function(e) {
      if (e.target.matches(".heyhey")) {
        console.log("You clicked the dropdown menu");
      } else {
        console.log("You clicked somewhere else");
        el.style.display = "none";
      }
    } 

代码:

window.onclick = function(e) {
    if (e.target.matches(".heyhey")) {
        console.log("You clicked the dropdown menu");
        el.style.display = "block"; // Shows the element
        e.preventDefault(); // Prevents propagation
    } else {
        console.log("You clicked somewhere else");
        el.style.display = "none";
    }
}

.preventDefault

event.preventDefault 停止传播,JS 默认调用 onclick 父元素,这会停止 onclick 处理程序的重复计数。

el.style.display = "阻止";

这会更改 none 的 display 样式,从而显示该元素。这可以更改为除 none.

之外的任何其他显示样式

我认为你应该将 span 移到标签上方:

<span class="heyhey">⋮</span>
<label for="checkId">
    <input id="checkId" type="checkbox" name="menu" />
</label> 

并将以下代码添加到您的条件中:

console.log("You clicked the dropdown menu");
el.style.display = "block";