1.编写导航,下拉菜单等style样式
- 导航:主菜单,子菜单,颜色,字体,大小,列表,链接,边距等,如下图:
- 对应代码如下:
<!DOCTYPE html>
<html lang="en"><head>
<mate charset="UTF-8" /><mate name="viewport" cantent="width=device-width ,initial-scale=1.0" />
<title>php中文网</title><style>
*{margin: 0;
padding: 0;box-sizing: border-box;
}a{
color: #bbb;text-decoration: none;
}#nav{
background-color: black;height: 50px;
line-height: 50px;}
li{list-style: none;
margin: 0 10px;float: left;
}#nav > li > a:hover{
color: white;}
#nav >li {position: relative;
}#nav > li > ul{
position: absolute;top: 50px;
width: 180px;border: 1px solid #aaa;
border-top: none;}
#nav > li > ul > li a {display: inline-block;
height: 50px;color: #444;
}ul.sub li:hover {
backgruond-color: #eee;}
#nav > li > ul {display: none;
}</style>
</head><body>
<ul id="nav"><li><a href="">首页</a></li>
<li><a href="">视频教程</a></li><li>
<a href="">资源下载</a><ul>
<li><a href="">PHP工具</a></li><li><a href="">在线手册</a></li>
<li><a href="">学习课件</a></li><li><a href="">网站源码</a></li>
</ul></li>
<li><a href="">社区问答</a></li><li>
<a href="">技术文章</a><ul>
<li><a href="">头条</a></li><li><a href="">博客</a></li>
<li><a href="">php教程</a></li><li><a href="">php框架</a></li>
</ul></li>
</ul></body>
</html>
2.编写导航,下拉菜单等javascript样式
- 先要获取所有主菜单,另外要判断主菜单下面有没有子菜单,如果有,鼠标移入主菜单时,那么就显示子所有菜单,鼠标移出时,关掉子菜单。
- 运用事件监听,事件委托,(捕获:从外向内、冒泡:从内向外)代码如下:
<script>
const navs = document.querySelectorAll(“#nav > li”);navs.forEach(function (nav) {
nav.addEventListener(“mouseover”, showSubMenu);nav.addEventListener("mouseout", closeSubMenu);
});function showSubMenu(ev) {
if (ev.target.nextElementSibling !== null) {ev.target.nextElementSibling.style.display = "block";
}}
function closeSubMenu(ev) {if (ev.target.nodeName === "A" && ev.target.nextElementSibling !== null) {
ev.target.nextElementSibling.style.display = “none”;}
}</script>