今天给大家分享一种用JS写的导航栏,虽然我们工作中不会使用JS来做导航栏,为了练习我们用JS来做一个JS导航栏
该注释的地方我都给大家注释上了
思路:给所有的 li 加上 鼠标移入事件当鼠标移入时会触发事件,由于事件的冒泡机制,每次二级导航栏里的事件触发时同时会触发父级 li 的事件
调试时可以用e.stopPropagation()阻止事件冒泡来看看冒泡和不冒泡的区别
<Meta charset="UTF-8">
*{margin:0;padding:0;}
ul,li{list-style: none;}
/* 一级导航样式 */
#nav{
width:100%;
height: 40px;
background: #000;
}
#nav>li{
float: left;
position: relative;
}
#nav>li>a{
float: left;
width: 80px;
height: 40px;
color: #fff;
text-decoration: none;
line-height: 40px;
text-align: center;
}
#nav li>.active{
background: yellow;
}
#nav>li>ul>li>.active{
background: red;
}
#nav>li>ul{
width: 100px;
background: #000;
position: absolute;
left: 0;
top: 40px;
display: none;
}
#nav>li>ul>li>a{
text-decoration: none;
color: #fff;
line-height: 30px;
text-align: center;
width: 100px;
height: 30px;
display: block;
}