代码主体及说明
Javascript部分:
/** * @函数名:flexScroll * @功能:滚动超出一定高度,指定元素悬浮 * @两个参数:target_id:目标元素id;topEle:限定滚动高度,超过之后,导航条悬浮 * @调用方式:e.g.:flexScroll('nav',80); * @author:Kevin 2015/8/14 */ function flexScroll(target_id,topEle){ window.onscroll=function(){ var scrollTop=document.documentElement.scrollTop || document.body.scrollTop; var scrollNav=document.getElementById(target_id); if(scrollTop>topEle){ scrollNav.classList.add('slideDown'); scrollNav.style.position="fixed"; scrollNav.style.top="0"; }else{ scrollNav.classList.remove('slideDown'); scrollNav.style.position="static"; } } }
Css动画部分:
.slideDown { -webkit-animation: slideDown .5s linear; animation: slideDown .5s linear; -webkit-animation-fill-mode: both; -moz-animation-fill-mode: both; -o-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes slideDown{ 0%{-webkit-transform:translateY(-2rem)} 100%{-webkit-transform:translateY(0)} }
应用示例
在线演示:http://codepen.io/anon/pen/VLNBgN
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>JavaScript:浮动的导航条</title> <style type="text/css"> * { margin: 0; padding: 0; } .content { 640px; height: 1800px; margin: 0 auto; background-color: #f5f5f5; } .nav { line-height: 40px; 640px; height: 40px; background-color: #333; } .nav li { position: relative; float: left; 25%; list-style: none; text-align: center; color: #fff; } .nav li:after { content: ''; display: block; position: absolute; top: 0; right: 0; bottom: 0; 1px; height: 20px; margin: auto; background-color: #999; } .nav li:last-child:after { display: none; } .placehold { 100%; height: 80px; background-color: red; } /*动画效果*/ .slideDown { -webkit-animation: slideDown .5s linear; animation: slideDown .5s linear; -webkit-animation-fill-mode: both; -moz-animation-fill-mode: both; -o-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes slideDown { 0% { -webkit-transform: translateY(-2rem); } 100% { -webkit-transform: translateY(0); } } </style> </head> <body> <div class="content"> <!--占位--> <div class="placehold"></div> <!--代码主体--> <div class="nav" id="nav"> <ul> <li>足球</li> <li>篮球</li> <li>苹果</li> <li>芒果</li> </ul> </div> </div> <script> function flexScroll(target_id,topEle){ window.onscroll=function(){ var scrollTop=document.documentElement.scrollTop || document.body.scrollTop; var scrollNav=document.getElementById(target_id); if(scrollTop>topEle){ scrollNav.classList.add('slideDown'); scrollNav.style.position="fixed"; scrollNav.style.top="0"; }else{ scrollNav.classList.remove('slideDown'); scrollNav.style.position="static"; } } } //调用 flexScroll('nav',80); </script> </body> </html>