1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>adsorption</title> 6 <style type="text/css"> 7 *{ margin: 0; padding: 0; } 8 .header-wrap{ width: 100%; } 9 .header-hd{ width: 980px; height: 150px; margin: 0 auto; background-color: #ccc; } 10 .header-bd{ width: 980px; height: 40px; margin: 0 auto; background-color: green; } 11 .fixed{ position: fixed; width: 100%; } 12 .fixed .header-hd{ display: none; } 13 </style> 14 15 <script type="text/javascript"> 16 window.onload=function(){ 17 18 var headerWrap=document.getElementById('header-wrap'); 19 var scrollTop=0; 20 window.onscroll=function(){ 21 scrollTop=document.body.scrollTop||document.documentElement.scrollTop; 22 if(scrollTop>150){ 23 headerWrap.className='fixed'; 24 }else{ 25 headerWrap.className='header-wrap'; 26 } 27 } 28 29 } 30 </script> 31 </head> 32 <body style="height:3000px;"> 33 34 35 <div id="header-wrap" class="header-wrap"> 36 <div class="header-hd"></div> 37 <div class="header-bd"></div> 38 39 40 </div> 41 </body> 42 </html>
我自己的方法是:
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>adsorption</title> 6 <style type="text/css"> 7 *{ margin: 0; padding: 0; } 8 .header-hd{ width: 980px; height: 150px; margin: 0 auto; background-color: #ccc; } 9 .header-bd{ width: 980px; height: 40px; margin: 0 auto; background-color: green; } 10 .fixed{ position: fixed; width: 980px; height: 40px; background-color: green; left:50%;margin-left:-490px; top:0px} 11 12 </style> 13 14 <script type="text/javascript"> 15 16 window.onload=function(){ 17 18 var headerbd=document.getElementById('bd'); 19 var scrollTop=0; 20 window.onscroll=function(){ 21 scrollTop=document.body.scrollTop||document.documentElement.scrollTop; 22 if(scrollTop>150){ 23 headerbd.className='fixed'; 24 }else{ 25 headerbd.className='header-bd'; 26 } 27 } 28 29 } 30 </script> 31 </head> 32 <body style="height:3000px;"> 33 34 35 36 <div class="header-hd"></div> 37 <div id="bd" class="header-bd"></div> 38 39 40 41 42 </body> 43 </html>