前言
记一次练习京东导航栏下拉菜单时的收获
一、下拉菜单的实现思路
使用一个div来放下拉菜单的内容,开始使用display:none属性将其隐藏,等到需要时再使用display:block使其出现,同时利用绝对定位的方式来使其脱离文档流来布局,防止影响原来的布局。
二、实现中出现的细节问题及解决办法
1.鼠标离开location进入location-list时就不再显示location-list
解决方法的代码如下:
<div class="outer">
<div class="inner">
<div class="current-location">
<div class="location">
哈
</div>
<div class="loaction-list">
</div>
</div>
</div>
</div>
</body>
/*将hover事件写在包含location和location-list的div上*/
.current-location:hover .loaction-list{
display: block;
}
2.京东网站上截出来的图上红色圈中location和location-list之间是没有边框的
利用location的下边来盖住location-list的上边的部分边框
解决方式的代码如下:
/* 利用它来盖住location-list上边框对应的部分 */
padding-bottom: 1px;
position: relative;
z-index: 9999;
/*解决hover事件时location出现抖动的情况,其实就是因为hover后出现了边框而hover前没有的原因*/
border: 1px solid transparent;
border-bottom: none;
}
.current-location:hover .location{
border: 1px solid grey;
border-bottom: none;
background-color: white;
}
总结
最后放上全部css代码以及效果图:
/* 设置整体 */
.outer{
width: 100%;
height: 30px;
background-color: #e3e4e5;
}
/* 使导航条居中 */
.inner{
height: 30px;
width: 1190px;
background-color: #e3e4e5;
margin: 0 auto;
/* 给location-list的定位做参照物 */
position: relative;
}
.current-location{
width: 30px;
}
/* 解决因current-location内的location的浮动和location-list的绝对定位导致的高度塌陷问题 */
.current-location::before,
.current-location::after{
content: '';
display: table;
clear: both;
}
/* 设置location大小 */
.current-location .location{
float: left;
width: 30px;
height: 29px;
line-height: 29px;
text-align: center;
/* 利用它来盖住location-list上边框对应的部分 */
border: 1px solid transparent;
border-bottom: none;
padding-bottom: 1px;
position: relative;
z-index: 9999;
}
.current-location:hover .location{
border: 1px solid #e3e4e5;
border-bottom: none;
background-color: white;
}
/* 设置locataion-list的大小,并让其脱离文档流布局 */
.current-location .loaction-list{
width: 50px;
height: 50px;
border: 1px solid #e3e4e5;
display: none;
position: absolute;
top: 30px;
left: 0px;
/* 避免后续脱离文档流的元素盖住它 */
z-index: 999;
}
.current-location:hover .loaction-list{
display: block;
}