面向对象吸顶条

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{margin:0;padding:0;}
        .Suction_cap{100%;height:100px;overflow:hidden;background:skyblue;}
        .main{1200px;height:1500px;}
    </style>
</head>
<body>
<div class="box">
    <div id="Suction_cap" class="Suction_cap">
        头部
    </div>
    <div class="main">
           测试<br/>
           测试<br/>
           测试<br/>
           测试<br/>
           测试<br/>
    </div>
</div>
<script>
    function Suction_cap(obj){
        this.ele=document.getElementById(obj)||document.getElementsByClassName(obj)[0];
        this.height=this.ele.offsetHeight;
        this.copy=document.createElement('div');
        this.parent_ele=this.ele.parentNode;
        var _this=this;
        window.onscroll=function(){
            var scrollT = document.documentElement.scrollTop || document.body.scrollTop;
            if(scrollT>0){
                _this.insertAfter( _this.copy, _this.ele);
                _this.copy.style.height=_this.getStyle(_this.ele,'height');
                _this.copy.style.display='block';
                _this.ele.style.position='fixed';
                _this.ele.style.boxShadow="0 0 5px #888";
            }else{
                _this.parent_ele.removeChild(_this.copy);
                _this.ele.style.display='block';
                _this.ele.style.position='relative';
                _this.ele.style.boxShadow="0 0 0 #fff";
            }
        }
    }
    Suction_cap.prototype.getStyle=function(obj,attr){
        if(obj.currentStyle)
        {
            return obj.currentStyle[attr];
        }
        else
        {
            return getComputedStyle(obj, false)[attr];
        }
    }
    Suction_cap.prototype.insertAfter=function( newElement, targetElement){
        var parent = targetElement.parentNode;
        if ( parent.lastChild == targetElement )
        {
            parent.a( newElement );
        }
        else
        {
            parent.insertBefore( newElement, targetElement.nextSibling );
        }
    }
    var obj=new Suction_cap('Suction_cap');
</script>
</body>
</html>

  

原文地址:https://www.cnblogs.com/learnings/p/7000231.html