介绍一款纯CSS和JS实现的下拉菜单(Dropdown Menu)

洼地云 ai-quyi.png

除了常见是使用Bootstrap来实现Dropdown菜单,这里介绍一种简单的、方便的、纯CSS实现的Dropdown Menu,可能对平时的工作学习会有些帮助,这篇文章转载自「How TO – Clickable Dropdown」,本文在原文的基础上摘录整理如下:

HTML部分代码

<div class="dropdown">
   <button onclick="myFunction()" class="dropbtn">Dropdown</button>
   <div id="myDropdown" class="dropdown-content">
       <a href="#">Link 1</a>
       <a href="#">Link 2</a>
       <a href="#">Link 3</a>
  </div>
</div>

CSS部分代码

/* Dropdown Button */
.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
    background-color: #3e8e41;
}

/* The container <div> - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index:99;/*解决页面有其他内容时被覆盖隐藏的问题,z-index的值越大,意味这一层在越上面,要使z-index生效,仅当position的值为absolute,relative或fixed 其中一个即可*/
}

/* Links inside the dropdown */
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

JS部分代码

/* 当用户点击button,dropdown下来菜单会来回切换隐藏和现实*/
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

效果预览

效果图如下

完整代码地址:「How TO – Clickable Dropdown

赞(0)
未经允许禁止转载:优米格 » 介绍一款纯CSS和JS实现的下拉菜单(Dropdown Menu)

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系

登录

找回密码

注册