这是一款效果非常酷的jQuery和css3全屏弹出式导航菜单特效插件。
HTML结构
html结构使用一个<header>作为wrapper。里面放logo、登录/注册按钮和用于触发全屏导航菜单的触发按钮。全屏导航菜单放置在header外面,为它使用easier的 CSS transformation效果。
<header class="cd-header"> <div class="cd-logo"><!-- ... --></div> <nav> <ul class="cd-secondary-nav"> <li><a href="#0">Log In</a></li> <li><a href="#0">Register</a></li> </ul> </nav> <!-- cd-nav --> <a class="cd-primary-nav-trigger" href="#0"> <span class="cd-menu-text">Menu</span><span class="cd-menu-icon"></span> </a> <!-- cd-primary-nav-trigger --> </header> <nav> <ul class="cd-primary-nav"> <li class="cd-label">About us</li> <li><a href="#0">The team</a></li> <li><a href="#0">Our services</a></li> <li><a href="#0">Our projects</a></li> <li><!-- ... --></li> </ul> </nav> <main> <!-- content --> </main>
CSS样式
为了制作全屏菜单的滑动效果,我们结合使用了CSS3 transitions和transformations。开始时,导航菜单被隐藏,它被放置在屏幕的上方(translateY(-100%))。当用户点击了触发按钮.cd-primary-nav-trigger,我们使用jQuery为导航菜单添加class .is-visible。在transition属性中使用transform 使动画更加平滑。
.cd-primary-nav { /* by default it's hidden - on top of the viewport */ position: fixed; left: 0; top: 0; height: 100%; width: 100%; transform: translateY(-100%); transition-property: transform; transition-duration: 0.4s; } .cd-primary-nav.is-visible { transform: translateY(0); }
对于顶部菜单的滑动显示效果-顶部菜单在用户往上滚动鼠标时出现,我们需要创建一些class并用jQuery来控制它们。默认情况下,顶部导航菜单是绝对定位的:意思是它会随内容一起滚动。当顶部菜单不可见时,我们给它class .is-fixed,将它的定位从absolute改变为fixed,并将它放在窗口的右上方(top: -80px)。当用户往上滚动页面,我们给顶部菜单.is-visible,使它从Y轴往下移动(translate3d(0, 100%, 0))。
.cd-header { position: absolute; top: 0; left: 0; background: transparent; height: 80px; width: 100%; transition: background-color 0.3s; } .cd-header.is-fixed { /* when the user scrolls down, we hide the header right above the viewport */ position: fixed; top: -80px; background-color: rgba(2, 23, 37, 0.96); transition: transform 0.3s; } .cd-header.is-visible { /* if the user changes the scrolling direction, we show the header */ transform: translate3d(0, 100%, 0); }
JAVASCRIPT
当用户开始滚动鼠标,我们需要检查是向上还是向下滚动,为顶部菜单添加/移除相应的class。
$(window).on('scroll', { previousTop: 0 }, function () { var currentTop = $(window).scrollTop(); //check if user is scrolling up if (currentTop < this.previousTop ) { //if scrolling up... //add class 'is-visible' to the main navigation //if currentTop == 0, remove 'is-fixed' and 'is-visible' classes } else { //if scrolling down... //add the 'is-fixed' class to the main navigation as soon as it is no longer visible //add class 'is-visible' to the main navigation } //set previousTop for the next iteration this.previousTop = currentTop; } );
注意,顶部菜单的上下滑动效果只用在大屏幕(分辨率大于1170px)的浏览器上才有效果。