js实现吸顶效果

 
 <style type="text/css">
 
div {
            width: 100%;
            height: 100px;
            margin-bottom: 15px;
            background-color: pink;
        }
        
        #red {
            background-color: red;
        }
        body {
            height: 3000px;
        }
</style>
  <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div id="red"></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
 
 <script>
        var oDiv = document.getElementById("red");
        //div在页面的占位高,div到body的距离
        var otop = oDiv.offsetTop;
        //页面滚动
        window.onscroll = function() {
           //获取页面的滚动距离
            var oheight = document.documentElement.scrollTop || document.body.scrollTop;
            //滚动到一定位置 div固定到顶部 js实现吸顶
            if (otop < oheight) {
                oDiv.style.position = "fixed";
                oDiv.style.top = 0;
            } else {
                oDiv.style.position = "relative";
            }
        }
    </script>


评论