中部导航吸顶

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         *{margin: 0;padding: 0;list-style: none;border:none}
 8         img{vertical-align: top;width: 100%;}
 9         section{width: 70%;margin: 0 auto;}
10         .nav{
11             position: fixed;
12             left: 0;
13             top:0;
14             width: 100%;
15         }
16 
17     </style>
18 </head>
19 <body>
20    <header id="head">
21        <img src="images/top.png" alt="">
22    </header>
23    <nav id="nav">
24        <img src="images/nav.png" alt="">
25    </nav>
26    <section>
27        <img src="images/body01.png" alt="">
28        <img src="images/body02.png" alt="">
29    </section>
30 
31 <script src="js/myFunc.js"></script>
32 <script>
33     window.onload = function () {
34         // 1. 求出offsetHeight
35         var nav_top_height = $("nav").offsetTop;
36 
37         // 2. 监听窗口滚动
38         window.onscroll = function () {
39             var scroll_top_height = scroll().top;
40             console.log(scroll_top_height);
41 
42             // 2.1 判断
43             if(scroll_top_height >= nav_top_height){
44                  $("nav").className = "nav";
45             }else {
46                 $("nav").className = "";
47             }
48         }
49     }
50 </script>
51 </body>
52 </html>
 1 function scroll() {
 2     if(window.pageYOffset !== null){
 3         return {
 4             top: window.pageYOffset,
 5             left: window.pageXOffset
 6         }
 7     }else if(document.compatMode === "CSS1Compat"){ // W3C
 8         return {
 9             top: document.documentElement.scrollTop,
10             left: document.documentElement.scrollLeft
11         }
12     }
13 
14     return {
15         top: document.body.scrollTop,
16         left: document.body.scrollLeft
17     }
18 }
19 
20 
21 function $(id) {
22     return typeof id === "string" ? document.getElementById(id) : null;
23 }

 

 

posted @ 2019-07-18 22:58  疏影横斜水清浅  阅读(157)  评论(0编辑  收藏  举报