纯CSS3实现导航下拉效果
本文作为前端动效课堂的开篇,我们先从一个比较简单的效果入门。相信大家在制作页面时首先要做的就是导航栏的下拉效果。导航栏是一个网站的索引,是seo的灵魂。在css3出来之前,我们会借助JQuery去实现导航下拉特效,在CSS3问世以后,我们可以简单地通过HTML+CSS3实现导航交互效果。下面就是导航栏的一个demo效果,鼠标移到“HTML教程”之后会滑出二级导航:
HTML代码:
<div id="effect-nav">
<div>
<a>首页</a>
</div>
<div>
<a>
HTML教程
</a>
<div class="sub">
<a>html教程</a>
<a>html5教程</a>
</div>
</div>
<div>
<a>JS教程</a>
</div>
<div>
<a>CSS教程</a>
</div>
</div>
CSS3代码:
#effect-nav {
display: flex;
flex-flow: row nowrap;
justify-content: stretch;
width: 100%;
height: 50px;
background-color: #2c3e50;
box-sizing: border-box;
}
#effect-nav > div {
position: relative;
padding: 0 20px;
}
#effect-nav > div a {
display: flex;
height: 100%;
align-items: center;
color: #ecf0f1;
cursor: pointer;
}
#effect-nav > div a:hover {
color: #2ecc71;
}
#effect-nav .sub {
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 51px;
background-color: #2c3e50;
overflow: hidden;
max-height: 0;
transition: all linear 0.4s;
-webkit-transition: all linear 0.4s;
-moz-transition: all linear 0.4s;
-ms-transition: all linear 0.4s;
-o-transition: all linear 0.4s;
}
#effect-nav > div:hover .sub {
max-height: 300px;
}
#effect-nav .sub a {
padding: 12px;
}
知识点提炼
- html的导航结构需要提前写好,这种带有多级导航的dom一般需要互相嵌套,我们可以从示例代码中看到,sub这个div是嵌套在对应的一级导航条目中的。
- 我们用了
transition
作为导航下拉动画的过渡引擎,这里需要注意,我们是针对max-height
过渡,而不是height
。如果我们使用height
控制二级导航,那么在hover状态必然会设置height
为auto
,这样css3的动画引擎无法得知二级导航的最终高度,导致过渡动画丢失,因此这里使用max-height
规避该问题。当然max-height
的结束值需要根据二级导航的最大高度进行调整。 - 整个动画的实现依赖了一个css3选择器:
#effect-nav > div:hover .sub
。这个选择器的意思就是控制被选中状态的一级导航下的二级导航样式,这句话可以好好体会一下。
希望大家可以根据这个例子举一反三,做出更多导航特效!
(全文完)