代码-JS之下拉菜单
效果:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!--编写CSS-->
<style>
*{
padding:0;
margin:0;
}
ul,li{
list-style: none;
}
body>ul>li>a{
display: block;
width:100px;
height:20px;
background-color: hotpink;
}
ul ul li a{
display: block;
width:100px;
height:20px;
background-color: skyblue;
}
ul ul {
display: none;
}
</style>
</head>
<body>
<!--编写HTML-->
<ul>
<li>
<a href="#">顶级菜单一</a>
<ul>
<li><a href="#">1.1</a></li>
<li><a href="#">1.2</a></li>
<li><a href="#">1.3</a></li>
</ul>
</li>
<li>
<a href="#">顶级菜单二</a>
<ul>
<li><a href="#">2.1</a></li>
<li><a href="#">2.2</a></li>
<li><a href="#">2.3</a></li>
</ul>
</li>
<li>
<a href="#">顶级菜单三</a>
<ul>
<li><a href="#">3.1</a></li>
<li><a href="#">3.2</a></li>
<li><a href="#">3.3</a></li>
</ul>
</li>
</ul>
<!--编写JS-->
<script>
//获取顶级菜单
var ones = document.querySelectorAll('body>ul>li>a');
//给顶级菜单绑定单机事件
for(var i=0; i<ones.length; i++){
ones[i].onclick = function () {
//获取子菜单
var son = this.parentNode.children[1];
if(son.style.display != 'block'){
son.style.display = 'block';
}else{
son.style.display = 'none';
}
}
}
</script>
</body>
</html>
Copyright [2018] by [羊驼可以吃吗] form [https://www.cnblogs.com/phpisfirst/]