目标是当鼠标悬浮在导航栏上时,出现指定的二级菜单。
首先先将基本的导航框架写好。
html和css代码
主页
介绍
技能
关于
.clearfix:after{content: ''; display: block; clear: both;}
*{margin: 0; padding: 0;}
ul, ol{list-style: none;}
a{text-decoration: none; cursor: pointer;}
nav{position: fixed; box-sizing: border-box; width: 100%; padding:12px; background: #fdf5e6;}
.topNavBar > ul{float: right;}
.topNavBar > ul > li{float: left; margin: 0 16px;}
效果如下
接下来就是写对应的二级菜单,这个二级菜单ul的位置很关键,可以写在一级导航li的a里面
技能
- javascript
- html
- css
也可以写在a外面。
技能
- javascript
- html
- css
为了不使a标签变得复杂和结构混乱,我们选择后者。(这才是正常人的做法吧- -!)
为了不让二级菜单占据父元素的宽度,我们让它定位以脱离文档流。
.topNavBar > ul > li > ul{
padding: 8px;
position: absolute;
top: 100%;
background: white;
white-space: nowrap;
box- shadow: 0 0 5px rgb(0, 0, 0, 0.5);
}
absolute定位后,li元素会被压缩,nowrap禁止换行。
到目前为止,这个顶部导航栏的主干的html部分和css部分基本完成,就剩下js部分了。
因为我们是想通过鼠标悬浮显示二级菜单,那么我们只需要一开始就把二级菜单隐藏,当鼠标移动到一级导航时显示二级菜单就好了。
let liTags = document.querySelectorAll(".topNavBar > ul > li");
for (let i=0; i
liTags[i].onmouseenter = function (e) {
let li = e.currentTarget;
li.classList.add("active");
}
liTags[i].onmouseleave = function (e) {
let li = e.currentTarget;
li.classList.remove("active");
}
}
.topNavBar > ul > li. > u{
display: none;
}
.topNavBar > ul > li.active > ul{
display: block;
}
现在一个干净简单的导航栏就完成了。