这是一款使用CSS3和少量jQuery代码制作的网页固定顶部菜单特效。该固定菜单特效在页面向下滚动的时候,页面顶部的banner区域会缩小直到消失,导航菜单则会跟着页面向下移动。配合CSS3过渡动画,效果非常时尚炫酷。
使用方法
HTML结构
该固定顶部菜单的HTML结构分为两个主要部分:一个是顶部菜单和banner,它们用<header>元素包裹。另一个是页面的内容区域div.wrapper。
<header>
<h1>Sticky Header Pow!</h1>
<nav>
<a href="">Home</a>
<a href="">About</a>
<a href="">Gallery</a>
<a href="">Contact</a>
</nav>
</header>
<div class="wrapper">
<section id='steezy'>
<h2>......</h2>
<p>......</p>
</section>
......
</div>
CSS样式
header元素以固定方式定位,100%的宽度,300像素的高度,并设置ease效果的CSS3过渡动画。
header {
width: 100%;
height: 300px;
background-color: #3498db;
text-align: center;
position: relative;
position: fixed;
top: 0;
overflow: hidden;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
-webkit-transition: all 0.5s ease;
transition: all 0.5s ease;
}
头部的h1元素在页面滚动时会跟着放大缩小,开始时为它设置ease效果的CSS3过渡动画。
header h1 {
font-size: 42px;
color: #fff;
line-height: 230px;
text-transform: uppercase;
font-weight: 100;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-webkit-transition: all 0.3s ease;
transition: all 0.3s ease;
}
水平导航菜单的基本样式如下:
header nav {
position: absolute;
bottom: 0;
height: 60px;
line-height: 60px;
width: 100%;
background-color: rgba(0, 0, 0, 0.1);
}
header nav a {
color: #fff;
display: inline-block;
padding: 10px 15px;
line-height: 1;
text-decoration: none;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
border-radius: 2px;
}
header nav a:hover {
-moz-box-shadow: 0 0 0 1px #fff;
-webkit-box-shadow: 0 0 0 1px #fff;
box-shadow: 0 0 0 1px #fff;
}
当页面开始滚动的时候,body元素被添加.sticky-header class,这时header的高度被设置为60像素,刚好等于水平导航菜单的高度。h1元素则使用transform: scale(0, 0)缩放到最小。
body.sticky-header {
padding-top: 100px;
}
body.sticky-header header {
height: 60px;
background-color: rgba(52, 152, 219, 0.9);
}
body.sticky-header header h1 {
-moz-transform: scale(0, 0);
-ms-transform: scale(0, 0);
-webkit-transform: scale(0, 0);
transform: scale(0, 0);
}
JavaScript
该固定顶部菜单使用jQuery代码来监听页面滚动事件,并在适当的时候为body元素添加和移除.sticky-header class。
$(function () {
$(window).scroll(function () {
var winTop = $(window).scrollTop();
if (winTop >= 30) {
$('body').addClass('sticky-header');
} else {
$('body').removeClass('sticky-header');
}
});
});