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