<!DOCTYPE html> |
<html> |
<head> |
<title> |
一个很精简的js二级导航栏 |
</title> |
<style type= "text/css" > |
nav ul { |
list-style: none; |
margin: 0; |
padding: 0; |
} |
nav ul li { |
display: inline-block; |
position: relative; |
} |
nav ul li a { |
color: #333; |
display: block; |
padding: 10px 20px; |
text-decoration: none; |
} |
nav ul li ul { |
background-color: #fff; |
border: 1px solid #ccc; |
display: none; |
position: absolute; |
top: 100%; |
left: 0; |
z-index: 999; |
padding: 10px; |
} |
nav ul li:hover ul { |
display: block; |
} |
nav ul li ul li { |
display: block; |
margin: 10px 0; |
} |
nav ul li ul li a { |
display: block; |
padding: 5px 0; |
} |
</style> |
</head> |
<body> |
<nav> |
<ul> |
<li> |
<a href= "#" >Home</a> |
</li> |
<li> |
<a href= "#" >About us</a> |
<ul> |
<li> |
<a href= "#" >Our team</a> |
</li> |
<li> |
<a href= "#" >Our history</a> |
</li> |
</ul> |
</li> |
<li> |
<a href= "#" >Portfolio</a> |
</li> |
<li> |
<a href= "#" >Contact us</a> |
</li> |
</ul> |
</nav> |
<script type= "text/javascript" > |
// 获取所有有下拉菜单的导航栏元素 |
var navItems = document.querySelectorAll( 'nav ul li' ); |
// 遍历导航栏元素 |
for ( var i = 0; i < navItems.length; i++) { |
var navItem = navItems[i]; |
var subMenu = navItem.querySelector( 'ul' ); |
// 如果当前导航栏元素有下拉菜单 |
if (subMenu) { |
// 为导航栏元素添加可收缩的事件监听器 |
navItem.addEventListener( 'click' , function (event) { |
event.preventDefault(); |
subMenu.classList.toggle( 'active' ); |
}); |
} |
} |
</script> |
</body> |
</html> |