实现的重点,是要将下拉菜单标题和下拉菜单内容放到一个母盒子里,在母盒子上绑定事件。下拉菜单的标题样式也可以写在母盒子里,然后将下拉菜单标题设置为span标签。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
text-decoration: none;
list-style:none;
}
header{
width: 100%;
height: 90px;
background-color: rgb(72, 119, 119);
}
.headerwrap{
width: 1000px;
height: 90px;
margin: 0 auto;
}
.nav1title{
color: rgb(240, 211, 211);
cursor: pointer;
line-height: 90px;
text-align: center;
width: 104px;
height: 90px;
}
.activeNav1title{
color: rgb(238, 243, 245);
background-color: darkblue;
}
.nav1boxtip{
color: brown;
width: 80px;
margin: 10px 10px;
height: auto;
height: 40px;
line-height: 40px;
border-bottom: gainsboro solid 1px;
text-align: center;
}
.nav1boxtip:hover{
color: rgb(51, 10, 255);
}
.nav1box{
display: none;
position: absolute;
top:90px;
border-bottom: gray solid 2px;
border-left: gray solid 2px;
border-right: gray solid 2px;
border-radius: 0 0 2px 2px;
}
.nav1{
position: relative;
width: 104px;
}
</style>
</head>
<body>
<header>
<div class="headerwrap">
<div class="nav1"><!--母盒子-->
<div class="nav1title">标题1</div><!--菜单标题-->
<div class="nav1box"><!--菜单内容-->
<li class="nav1boxtip">内容1</li>
<li class="nav1boxtip">内容2</li>
<li class="nav1boxtip">内容3</li>
<li class="nav1boxtip">内容4</li>
<li class="nav1boxtip">内容5</li>
</div>
</div>
</div>
</header>
</body>
<script>
var nav1=document.getElementsByClassName('nav1')[0];
var nav1box=document.getElementsByClassName('nav1box')[0];
var nav1title=document.getElementsByClassName('nav1title')[0];
nav1.addEventListener('mouseover',function(){
nav1box.style.display='block';
nav1title.classList.add('activeNav1title');
});
nav1.addEventListener('mouseout',function(){
nav1box.style.display='none';
nav1title.classList.remove('activeNav1title');
});
</script>
</html>