不使用时如何使下拉菜单崩溃



所以我有一个下拉菜单,当我单击它时,它可以正常工作,但是当我单击时,它会保持打开状态。我尝试使用Mouseout Mousedown OnClick Ondblick等,但它们都没有用。请帮助:(

[What I've tried][1]

附加click侦听器上的 document,如果单击元素为 img,则显示dropwdown else hide。

const menu = document.querySelector('#dropdown');
document.addEventListener('click', function(e) {
  menu.classList.toggle('show', e.target.tagName == "IMG");
});
.menu {
  float: right;
  margin: 24px;
  position: relative;
  display: inline-block;
}
.menu img {
  cursor: pointer;
}
.dropdown {
  position: absolute;
  z-index: 1;
  float: right;
  width: 150px;
  background-color: lightgray;
  top: 73px;
  right: -24px;
  display: none;
}
.dropdown a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
.dropdown a:hover {
  color: #B00D93;
  font-weight: bold;
}
.show {
  display: block;
}
<div class="menu" id="menu">
  <img src="https://s3.amazonaws.com/media.skillcrush.com/skillcrush/wp-content/uploads/2018/06/Screen-Shot-2018-06-13-at-8.07.34-PM.png" id="dropdownImg" alt="" width="45px" height="45px">
  <div class="dropdown" id="dropdown">
    <a href="">Home</a>
    <a href="">About Us</a>
    <a href="">Services</a>
    <a href="">Feedback</a>
  </div>
</div>

检查以下内容:https://jsfiddle.net/85yz7asd/

showHide = () => {
 var dropdown = document.getElementById("dropdown") 
 dropdown.style.display == "block" ?  dropdown.style.display = "none" : dropdown.style.display = "block"
 }

这是纯 html css 示例:

html

    <div class="dropdown">
        <div class="dropdown-btn">Hover Me</div>
        <ul class="dropdown-list">
            <li><a href="">Link #1</a></li>
            <li><a href="">Link #2</a></li>
            <li><a href="">Link #3</a></li>
        </ul>
    </div>

CSS

.dropdown {
    display: block;
    position: absolute;
}
.dropdown-btn {
    text-align: center;
    background-color: black;
        color: white;
    display: block;
    position: absolute;
    width: 200px;
    height: auto;
    padding: 10px;
    font-size: 16px;
    cursor: pointer;
}
.dropdown-list {
    position: relative;
    display: none;
    width: 200px;
    height: auto;
    list-style: none;
    margin-top: 40px;
    padding: 0;
}
.dropdown-list li a {
    text-align: center;
    text-decoration: none;
    display: block;
    padding: 10px;
    width: 200px;
    background-color: black;
        color: white;
    margin-top: 5px;
}
.dropdown-list li a:hover {
    background-color: grey;
        color: white;
}
.dropdown:hover .dropdown-list {
    display: block;
}

工作Js小提琴

如果要使用当前代码,请尝试使用。单击dropdownImg元素将打开菜单。单击其他任何地方都会关闭菜单。

https://jsfiddle.net/t6wpgjrd/

document.onclick = function(e) {
    if(e.target.id === "dropdownImg") {
      show();
    }
    else{
      hide();
  }
}

不要忘记从您的dropdownImg元素中删除onclickonblur属性。

最新更新