如何实现当div滚动到页面顶端的时候固定住

05月12日 14:53

阅读:2,172
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>
            如何让div滚动到顶部后固定
        </title>
        <style type="text/css">
            .wrapper{width:1000px;height:2000px;margin-left:auto;margin-right:auto;}
            .header{height:150px;} #nav_keleyi_com{padding:10px;position:relative;top:0;background:#125430;width:1000px;}
            a{display:inline-block;margin:0 10px;*display:inline;zoom:1;color:white;}
        </style>
    </head>

    <body>
        <div class="wrapper">
            <div class="header">
            </div>
            <div id="nav_keleyi_com">
                <a href="http://www.kaicz.com/web/" target="_blank">前端特效</a>
                <a href="http://www.kaicz.com/templet/" target="_blank">原创模板</a>
                <a href="http://www.kaicz.com/source/" target="_blank">开源程序</a>
                <a href="http://www.kaicz.com/blog/" target="_blank">好文分享</a>
                <a href="http://www.kaicz.com/tools/" target="_blank">在线工具</a>
                <a href="http://www.kaicz.com/daohang/" target="_blank">站长导航</a>
                <a href="http://www.kaicz.com/joke/" target="_blank">搞笑段子</a>
                <a href="http://www.kaicz.com/rank/" target="_blank">大神排行</a>
            </div>
        </div>
        <script type="text/javascript">
            function menuFixed(id) {
                var obj = document.getElementById(id);
                var _getHeight = obj.offsetTop;

                window.onscroll = function() {
                    changePos(id, _getHeight);
                }
            }
            function changePos(id, height) {
                var obj = document.getElementById(id);
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                if (scrollTop < height) {
                    obj.style.position = 'relative';
                } else {
                    obj.style.position = 'fixed';
                }
            }
        </script>
        <script type="text/javascript">
            window.onload = function() {
                menuFixed('nav_keleyi_com');
            }
        </script>
    </body>
</html>