1.HTML部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul class="nav">
<li>
<a href="#">微博</a>
<ul>
<li>
<a href="">私信</a>
</li>
<li>
<a href="">评论</a>
</li>
<li>
<a href="">@我</a>
</li>
</ul>
</li>
<li>
<a href="#">博客</a>
<ul>
<li>
<a href="">博客评论</a>
</li>
<li>
<a href="">未读提醒</a>
</li>
</ul>
</li>
<li>
<a href="#">邮箱</a>
<ul>
<li>
<a href="">免费邮箱</a>
</li>
<li>
<a href="">VIP邮箱</a>
</li>
<li>
<a href="">企业邮箱</a>
</li>
<li>
<a href="">新浪邮箱</a>
</li>
</ul>
</li>
</ul>
</body>
</html>
2.css部分
<style>
* {
padding: 0;
margin: 0;
}
li {
list-style: none;
}
a {
text-decoration: none;
font-size: 14px;
}
.nav {
margin: 200px;
}
.nav>li {
float: left;
width: 80px;
height: 40px;
text-align: center;
}
.nav li a {
display: block;
width: 80px;
height: 40px;
line-height: 40px;
border: 1px solid red;
}
.bg {
background-color: pink;
}
.nav ul li a:hover {
background-color: orange;
}
.nav ul {
display: none;
}
.bg {
background-color: pink;
color: #fff;
}
</style>
3.javascript部分
<script>
// 1. 获取元素 先是找到nav 再找到nav里面的所有的li 事件源
var nav = document.querySelector('.nav');
var lis = nav.children; // 得到3个小li
// 2.循环注册事件
for (var i = 0; i < lis.length; i++) {
//当鼠标在每一个li上的时候 让当前li的第二个孩子也就是ul显示
lis[i].onmouseover = function() {
this.children[0].className = 'bg';
this.children[1].style.display = 'block';
};
//当鼠标移出每一个li时候 让当前的li的第二个孩子也就是ul隐藏
lis[i].onmouseout = function() {
this.children[0].className = ' ';
this.children[1].style.display = 'none';
}
}
</script>