Div滚动到头以后置顶

发布时间 2023-03-31 16:55:21作者: 贾树丙
 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4     <meta charset="utf-8" />
 5     <title>Div滚动到头以后置顶</title>
 6 </head>
 7 <body style="height:2000px;">
 8 <div style="height: 200px"></div>
 9 <div id="nav_keleyi_com" style="position:relative;top:0;background:#00f;width:100px; height:100px">
10     Test Div
11 </div>
12 </div>
13 <script type="text/javascript" >
14     function menuFixed(id){
15         var obj = document.getElementById(id);
16         var _getHeight = obj.offsetTop;
17 
18         window.onscroll = function(){
19             changePos(id,_getHeight);
20         }
21     }
22     function changePos(id,height){
23         var obj = document.getElementById(id);
24         var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
25         if(scrollTop < height){
26             obj.style.position = 'relative';
27         }else{
28             obj.style.position = 'fixed';
29         }
30     }
31 </script>
32 <script type="text/javascript">
33     window.onload = function(){
34         menuFixed('nav_keleyi_com');
35     }
36 </script>
37 </body>
38 </html>