代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>下拉菜单</title>
<style>
/* 盒子模型有默认的margin padding值 */
* {
margin: 0px;
padding: 0px;
}
#nav {
background-color: #eee;
width: 500px;
height: 40px;
/* 居中 */
margin: 0 auto;
}
ul {
list-style: none;
}
ul li {
/* float浮动属性,值left向左浮动。 */
float: left;
/* width: 90px; 防止页面标题过长*/
/* padding: 0px 10px; 在a中添加 */
/* 行高 */
line-height: 40px;
text-align: center;
/* 便于二级菜单布局 */
position: relative;
}
a {
text-decoration: none;
color: black;
/* 变成块级元素 */
display: block;
padding: 0px 10px;
height: 40px;
}
a:hover {
background-color: #666;
color: white;
}
ul li ul li {
float: none;
background-color: #eee;
margin-top: 2px;
}
ul li ul {
/* position:absolute 绝定定位 ,生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。 */
/* 为了不影响一级菜单的布局 */
position: absolute;
left: 0px;
top: 40px;
display: none;
}
ul li ul li a:hover {
background-color: red;
}
ul li ul li a {
width: 80px;
}
</style>
<script>
function showSubMenu(e) {
// 通过"标签"获取HTML元素
var subMenu = e.getElementsByTagName("ul")[0];
subMenu.style.display = "block";
}
function hideSubMenu(e) {
var subMenu = e.getElementsByTagName("ul")[0];
subMenu.style.display = "none";
}
</script>
</head>
<body>
<div id="nav">
<ul>
<li><a href="https://www.youkuaiyun.com/">首页</a></li>
<!-- this 当前对象 -->
<li onmouseover="showSubMenu(this)" onmouseout="hideSubMenu(this)"><a href="#">服务中心</a>
<ul>
<li><a href="#">javascript</a></li>
<li><a href="#">jQuery</a></li>
<li><a href="#">Angular</a></li>
</ul>
</li>
<li onmouseover="showSubMenu(this)" onmouseout="hideSubMenu(this)"><a href="#">商家中心</a>
<ul>
<li><a href="#">商家规则</a></li>
<li><a href="#">招商入住</a></li>
<li><a href="#">商家品控</a></li>
</ul>
</li>
<li onmouseover="showSubMenu(this)" onmouseout="hideSubMenu(this)"><a href="#">网站导航</a>
<ul>
<li><a href="https://ai.taobao.com">淘宝</a></li>
<li><a href="https://www.baidu.com">百度</a></li>
<li><a href="https://www.csdn.com">csdn</a></li>
</ul>
</li>
<li><a href="#">联系我们</a></li>
</ul>
</div>
</body>
</html>
效果图: