javascript - 下拉菜单效果

标签 javascript css

我有一个下拉菜单,单击按钮时会出现该菜单,再次单击按钮时会消失。我想知道如何使菜单从下往上消失,而不是立即消失。我不要求确切的代码,只需要指出正确的方向。谢谢。

let nav = document.querySelector("nav");
let icon = document.querySelector(".mobile-icon");
console.log(nav);
icon.addEventListener("click", showMenu);

function showMenu() {
if (nav.style.display == "none"){
nav.style.display = "block";
} else {
    nav.style.display = "none";
}

}

最佳答案

我的解决方案是创建一个类,将菜单的高度设置为 0px,然后使用 JavaScript 打开和关闭它。

我在 JSFiddle 中创建了一个小模型,并对重要部分做了一些评论。

JSFiddle 的链接是 - https://jsfiddle.net/gmuz2m98/

这里是代码:

HTML -

<button> Hide/Show </button>

<ul>
  <li> Link 1 </li>
  <li> Link 2 </li>
  <li> Link 3 </li>
  <li> Link 4 </li>
</ul>

CSS-

ul {
  /* Give the ul a transition to run smoothly */
  transition: all .5s;
  list-style:none;
  padding:0;
  margin:20px 0px;
  background-color:#D6D6D6;

  /* Make sure overflow is hidden so when the hight is droped to 0px the li elements stay hidden */
  overflow:hidden;

  /* Give the ul a default hight to revert to, without this the transiton won't work */
  height:160px;
}

li {
  padding: 10px 20px;
}

/* This is the class that will be added with JavaScript */
.hide {
  height:0px;
}

JS-

// Assign the ul and the button to a variable
var ul = document.getElementsByTagName('ul')[0],
        btn = document.getElementsByTagName('button')[0];

// Create a function that lets the class 'hide' be toggled on and off the ul
function dropDown(){
    ul.classList.toggle('hide');
}

// Assign the function to the button with an EventListener
btn.addEventListener('click',dropDown,false);

关于javascript - 下拉菜单效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47578035/

相关文章:

css - 在 css 中使用 starts with selector 是否有效?

javascript - 为什么es6需要构造函数?

javascript - 使用 javascript 左右平移 DIV 元素

除非我刷新,否则 JavaScript/Coffeescript 不会执行

javascript - 将鼠标悬停在图像和链接上时颜色发生变化

jquery - 具有方向问题的响应式 slider 面板

javascript - 干净地链接 jQuery ajax 请求

javascript - 获取 "message":"Admin validation failed" Mongoose 、node.js 中的错误

html - css 中的 id 与 class 声明

css - 如何在悬停时保持直通