- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>无标题文档</title>
- <style>
- .h200{ height:200px;}
- .h1800{ height:1800px;}
- .test{width:460px;height:60px;border:solid 1px #FF6600;background:#F90;position:absolute;}
- .box_fixed{position:fixed;top:0px;}
- </style>
- </head>
- <body>
- <div class="h200"></div>
- <div class="test" id="test">我来测试下</div>
- <div class="h1800"></div>
- <script type="text/javascript">
- var scrollFixed = function(elem){
- this.elem = elem;
- this.elemTop = scrollFixed.prototype.getElementTop(elem);
- }
- scrollFixed.prototype = {
- getScrollTop : function(){
- if(document.documentElement && document.documentElement.scrollTop){
- return document.documentElement.scrollTop;
- }else if(document.body && document.body.scrollTop){
- return document.body.scrollTop;
- }
- },
- getElementTop : function(elem){
- var eTop = elem.offsetTop;
- var eParent = elem.offsetParent;
- if(eParent!=null){
- eTop +=eParent.offsetTop;
- eParenteParent = eParent.offsetParent;
- }
- return eTop;
- },
- onStart : function(){
- window.onscroll = function(that){
- return function(){ //javascript闭包
- if(that.getScrollTop()>that.elemTop){
- if(document.body){
- thatthat.elem.style.top = that.getScrollTop() + "px";
- }else{
- that.elem.className+= ' box_fixed';
- }
- }else{
- if(document.body){
- thatthat.elem.style.top = that.elemTop + 'px';
- }else{
- that.elem.className = "test";
- }
- }
- }
- }(this);
- }
- }
- </script>
- <script>
- var a = new scrollFixed(document.getElementById('test'));
- a.onStart();
- </script>
- </body>
- </html>
本文转自 涂根华 51CTO博客,原文链接:http://blog.51cto.com/tugenhua/759296,如需转载请自行联系原作者