js实现模拟下拉菜单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模拟下拉菜单t</title>
<style>
* {
margin: 0;
padding: 0;
}
ul,
li {
list-style: none;
}
body {
background-color: rgb(80, 79, 78);
}
.nav {
width: 300px;
height: 30px;
background-color: rgb(61, 53, 56);
margin: 0 auto;
border: 1px solid;
border: 1px solid white;
position: relative;
color: whitesmoke;
line-height: 30px;
text-indent: 2em;
}
.smallnav {
display: none;
}
ul {
position: absolute;
top: 30px;
border: 1px solid white;
}
li {
/* display: none; */
background-color: black;
width: 300px;
height: 30px;
color: whitesmoke;
border-bottom: 1px dotted whitesmoke;
line-height: 30px;
}
.smallnav li:hover {
background-color: rgb(211, 200, 180);
}
</style>
</head>
<body>
<div class="nav">
<div class="header">地下城与勇士</div>
<ul class="smallnav">
<li>地下城与勇士</li>
<li>魔兽世界(国服)</li>
<li>魔兽世界(台服)</li>
<li>热血江湖</li>
<li>大话西游||</li>
<li>QQ幻想世界</li>
</ul>
</div>
</body>
</html>
<script>
var oli = document.querySelectorAll("li");
var onav = document.querySelector(".nav");
var oheader = document.querySelector(".header");
var osmallnav = document.querySelector(".smallnav")
for (var i = 0; i < oli.length; i++) {//得到每个li
oli[i].onclick = function (e) {
oheader.innerHTML = this.innerHTML;
osmallnav.style.display = "none";
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;//阻止事件冒泡
}
oheader.onclick = function (e) {
osmallnav.style.display = "block";
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;//阻止事件冒泡
}
document.onclick = function () {
osmallnav.style.display = "none";
}
}
</script>