导航栏 滑到指定位置 固定住方法

 1 <!DOCTYPE HTML>
 2 <html lang="en-US">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <link rel="stylesheet" type="text/css" href="css/base.css" media="all"/>
 7     <style type="text/css">
 8     .wrapper{width:1000px;height:2000px;margin-left:auto;margin-right:auto;}
 9     .header{height:150px;}
10     #nav{padding:10px;position:relative;top:0;background:black;width:1000px;}
11     a{display:inline-block;margin:0 10px;*display:inline;zoom:1;color:white;}
12     </style>
13 </head>
14 <body>
15     <div class="wrapper">
16         <div class="header"></div>
17         <div id="nav">
18             <a href="#">11111</a>
19             <a href="#">22222</a>
20             <a href="#">33333</a>
21             <a href="#">44444</a>
22             <a href="#">55555</a>
23         </div>
24     </div>
25 </body>
26 </html>
27 <script type="text/javascript" src="menuFixed.js"></script>
28 <script type="text/javascript">
29 window.onload = function(){
30     menuFixed('nav');
31 }
32 </script>

 

方式一:

 1 //js代码
 2 
 3 function menuFixed(id){
 4     var obj = document.getElementById(id);
 5     var _getHeight = obj.offsetTop;
 6     
 7     window.onscroll = function(){
 8         changePos(id,_getHeight);
 9     }
10 }
11 function changePos(id,height){
12     var obj = document.getElementById(id);
13     var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
14     if(scrollTop < height){
15         obj.style.position = 'relative';
16         //obj.style.position = 'fixed';此处的fixed 与 relative取决于你初始设定的div位置有关
17         //obj.style.top = "200px";
18     }else{
19         obj.style.position = 'fixed';
20         //obj.style.position ='fixed';
21        // obj.style.top = "101px";
22     }
23 }
24 
25 window.onload=function(){menuFixed("dh");}//调用函数

 

 方式二:

 1 //jquery 代码
 2 
 3 $(function () 
 4 {
 5 var ie6 = /msie 6/i.test(navigator.userAgent)
 6 , dv = $('#dh'), st;
 7 dv.attr('otop', dv.offset().top); //存储原来的距离顶部的距离
 8 $(window).scroll(function () //scroll函数,滚动函数
 9 {
10 st = Math.max(document.body.scrollTop || document.documentElement.scrollTop);
11 if (st >= parseInt(dv.attr('otop')))
12 {
13 if (ie6) {//IE6不支持fixed属性,所以只能靠设置position为absolute和top实现此效果
14 dv.css({ position: 'absolute', top: st });
15 }
16 else if (dv.css('position') != 'fixed') 
17 dv.css({ 'position': 'fixed', top: 0 });
18 } 
19 else if (st < parseInt(dv.attr('otop'))) 
20 dv.css({ 'position': 'absolute',top:500px });
21 });
22 });

 



posted @ 2015-08-19 22:31  其实哥很宅  阅读(861)  评论(0编辑  收藏  举报