我正在尝试学习JavaScript,但在纯JS中找到简单的样本并不是一件容易的事。我在jQuery中编写了以下代码,但是很想在纯JS中创建一个下拉导航栏。关于如何处理代码的任何想法?
这是我在HTML和jQuery中所做的:
<nav>
<ul>
<a href='#' id='logo'><h2>QuokkaCentral</h2></a>
<a href='#' id='hamburger'><li>MENU ☰</li></a>
<a href='#' id='cross'><li>CLOSE X</li></a>
<div id='navbar'>
<a href='#' class='menu'><li>Quokka</li></a>
<a href='#' class='menu'><li>Rottnest</li></a>
<a href='#' class='menu'><li>Find us</li></a>
<a href='#' class='menu'><li>Social</li></a>
</div>
</ul>
</nav>
$("#navbar").hide();
$("#cross").hide();
$("#hamburger").click(function(){
$("#navbar").slideDown(300);
$("#hamburger").hide();
$("#cross").show();
});
$("#cross").click(function(){
$("#navbar").slideUp(300);
$("#cross").hide();
$("#hamburger").show();
});
答案 0 :(得分:0)
这就是我最终的结果。希望它有所帮助。
var navbar = document.getElementById('navbar');
var cross = document.getElementById('cross');
var hamburger = document.getElementById('hamburger');
cross.style.display = "none";
navbar.style.display = "none";
hamburger.addEventListener('click', function() {
navbar.className -= " slideUp";
navbar.className += " slideDown";
navbar.style.display = "block";
hamburger.style.display = "none";
cross.style.display = "block";
});
cross.addEventListener('click', function() {
navbar.className -= " slideDown";
navbar.className += " slideUp";
setTimeout(function() {
navbar.style.display = "none";
}, 300);
cross.style.display = "none";
hamburger.style.display = "block";
});
#navbar.slideDown {
animation-name: slideDown;
animation-duration: .3s;
}
#navbar.slideUp {
animation-name: slideUp;
animation-duration: .3s;
}
@keyframes slideDown {
0% {
display: none;
overflow: hidden;
height: 0px;
}
100% {
display: block;
overflow: hidden;
height: 72.2113px;
}
}
@keyframes slideUp {
0% {
display: block;
overflow: hidden;
height: 72.2113px;
}
100% {
display: none;
overflow: hidden;
height: 0px;
}
}
<nav>
<ul>
<a href='#' id='logo'>
<h2>QuokkaCentral</h2>
</a>
<a href='#' id='hamburger'>
<li>MENU ☰</li>
</a>
<a href='#' id='cross'>
<li>CLOSE X</li>
</a>
<div id='navbar'>
<a href='#' class='menu'>
<li>Quokka</li>
</a>
<a href='#' class='menu'>
<li>Rottnest</li>
</a>
<a href='#' class='menu'>
<li>Find us</li>
</a>
<a href='#' class='menu'>
<li>Social</li>
</a>
</div>
</ul>
</nav>