今天跟大家一起,使用 css3 transform 的几个简单属性,来简单实现一个交错过渡动效的导航菜单。效果如下:
DOM
我们以最最最~古老的企业站点导航为栗子,创建一个页面结构:
<ul class="nav-hover">
<li>
<a href="#nogo">首页 <span>Home</span></a>
</li>
<li>
<a href="#nogo">新闻 <span>News</span></a>
</li>
<li>
<a href="#nogo">产品 <span>Products</span></a>
</li>
<li>
<a href="#nogo">关于 <span>About</span></a>
</li>
<li>
<a href="#nogo">联系 <span>Contact</span></a>
</li>
</ul>
实现思路很简单,默认把所有动效元素先 translateY(x) 到父容器之外,鼠标 hover 到父容器的时候,再把它们都 translateY(0) 回来。
translateY(x) 中的 x 为动效元素的高度。
再为每个动效元素创建一个时间差,本例中为 0.06s,使其逐一进行,达到交错过渡的动态效果。
具体实现见 SCSS 文件的注释信息:
/* 导航交错过渡效果 */
/* -------------------------------------------- */
$nav-numbers: 5; // 菜单数量
$nav-bg: deepskyblue; // 菜单主背景色
.nav-hover {
// 重置间距,水平居中
margin: 0 auto;
padding: 0;
text-align: center;
// 去除子元素换行空字符引起的空隙
font-size: 0;
// 菜单横向行内排列
> li {
display: inline-block;
width: 200px;
list-style: none;
// 链接区域块状化
a {
display: block;
line-height: 60px;
text-align: center;
font-size: 24px;
color: white;
text-decoration: none;
// 溢出隐藏
overflow: hidden;
// 想让它动起来的东西,就叫【小动】吧
span {
display: block;
line-height: 40px;
font-size: 18px;
background: rgba(0, 0, 0, .12);
// 先把小动挪出父容器
transform: translateY(40px);
transition: .3s;
}
}
}
// hover 时,再把小动挪回来
&:hover span {
transform: translateY(0);
}
}
// 给每个菜单添加背景色,给每个小动添加延迟时间
@for $i from 0 through $nav-numbers {
.nav-hover > li:nth-child(#{$i + 1}) {
// 背景色渐深,只是为了区分效果,完全可以在前面设置成同一色值
background-color: darken($nav-bg, 5% * $i);
// 小动的延迟时间递增
span {
transition-delay: .06s * $i;
}
}
}
编译后的 CSS
上面的 SCSS 编译之后,完整的静态样式如下:
/* 导航交错过渡效果 */
/* -------------------------------------------- */
.nav-hover { margin: 0 auto; padding: 0; text-align: center; font-size: 0; }
.nav-hover > li { display: inline-block; width: 200px; list-style: none; }
.nav-hover > li a { display: block; line-height: 60px; text-align: center; font-size: 24px; color: white; text-decoration: none; overflow: hidden; }
.nav-hover > li a span { display: block; line-height: 40px; font-size: 18px; background: rgba(0, 0, 0, 0.12); transform: translateY(40px); transition: .3s; }
.nav-hover:hover span { transform: translateY(0); }
.nav-hover > li:nth-child(1) { background-color: deepskyblue; }
.nav-hover > li:nth-child(1) span { transition-delay: 0s; }
.nav-hover > li:nth-child(2) { background-color: #00ace6; }
.nav-hover > li:nth-child(2) span { transition-delay: 0.06s; }
.nav-hover > li:nth-child(3) { background-color: #0099cc; }
.nav-hover > li:nth-child(3) span { transition-delay: 0.12s; }
.nav-hover > li:nth-child(4) { background-color: #0086b3; }
.nav-hover > li:nth-child(4) span { transition-delay: 0.18s; }
.nav-hover > li:nth-child(5) { background-color: #007399; }
.nav-hover > li:nth-child(5) span { transition-delay: 0.24s; }
.nav-hover > li:nth-child(6) { background-color: #006080; }
.nav-hover > li:nth-child(6) span { transition-delay: 0.3s; }
效果还不错哦,赶快来试试吧!?