下拉菜单效果

时间:2017-11-30 16:24:09

标签: 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";
}

}

2 个答案:

答案 0 :(得分:2)

我的解决方案是创建一个类,将菜单的高度设置为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);

答案 1 :(得分:1)

以下是我的解决方案,您无法将transition用于height属性,因此我们使用max-height。问题是我们需要在px中设置高度才能使此解决方案正常工作,因此请使用此解决方法进行测试!

let nav = document.querySelector("nav");
let icon = document.querySelector(".mobile-icon");
icon.addEventListener("click", showMenu);
nav.querySelector("ul").style.margin = "16px 0px";
nav.style.maxHeight = nav.querySelector("ul").clientHeight + 32 + "px";
function showMenu() {
  nav.classList.toggle("hideThis");
}
nav{
  transition: max-height 0.5s ease-out;
  height:auto;
  overflow:hidden;
}
nav.hideThis{
  max-height:0px !important;
}
<button class="mobile-icon">toggle</button>
<nav>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
</nav>