1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  5. <title>无标题文档</title> 
  6. <style> 
  7. .h200{ height:200px;} 
  8. .h1800{ height:1800px;} 
  9. .test{width:460px;height:60px;border:solid 1px #FF6600;background:#F90;position:absolute;} 
  10. .box_fixed{position:fixed;top:0px;} 
  11. </style> 
  12. </head> 
  13.  
  14. <body> 
  15.     <div class="h200"></div> 
  16.     <div class="test" id="test">我来测试下</div> 
  17.     <div class="h1800"></div> 
  18. <script type="text/javascript"> 
  19.     var scrollFixed = function(elem){ 
  20.         this.elem = elem; 
  21.         this.elemTop = scrollFixed.prototype.getElementTop(elem);    
  22.     } 
  23.     scrollFixed.prototype = { 
  24.         getScrollTop : function(){ 
  25.             if(document.documentElement && document.documentElement.scrollTop){ 
  26.                 return document.documentElement.scrollTop;   
  27.             }else if(document.body && document.body.scrollTop){ 
  28.                 return document.body.scrollTop;  
  29.             }    
  30.         }, 
  31.         getElementTop : function(elem){ 
  32.             var eTop = elem.offsetTop; 
  33.             var eParent = elem.offsetParent; 
  34.             if(eParent!=null){ 
  35.                 eTop +=eParent.offsetTop; 
  36.                 eParenteParent = eParent.offsetParent;  
  37.             } 
  38.             return eTop;     
  39.         }, 
  40.         onStart : function(){ 
  41.             window.onscroll = function(that){ 
  42.                 return function(){          //javascript闭包 
  43.                     if(that.getScrollTop()>that.elemTop){ 
  44.                         if(document.body){ 
  45.                             thatthat.elem.style.top = that.getScrollTop() + "px";    
  46.                         }else{ 
  47.                             that.elem.className+= ' box_fixed';  
  48.                         }    
  49.                     }else{ 
  50.                         if(document.body){ 
  51.                             thatthat.elem.style.top = that.elemTop + 'px';   
  52.                         }else{ 
  53.                             that.elem.className = "test";    
  54.                         }    
  55.                     }    
  56.                 }    
  57.             }(this);     
  58.         }    
  59.     }  
  60. </script> 
  61. <script> 
  62.     var a = new scrollFixed(document.getElementById('test')); 
  63.         a.onStart(); 
  64. </script> 
  65. </body> 
  66. </html>