日期:2014-05-16  浏览次数:20401 次

jquery实现导航栏始终可见。
页面中有一个导航栏,导航栏距浏览器上边缘有一定的距离,正常情况下,向下拉浏览器的滚动条,导航栏会向上走,当拉到导航栏超过浏览器上边缘的以后,导航栏就不可见了,我想实现的是,当未超过浏览器上边缘拉滚动条,导航栏正常向上走,但是当滚动条的div的上边缘距离浏览器上边缘为0时,保证导航条始终在最上端,保持可见。当导航条拉回去后,导航栏又回复到原来的位置,求代码

------解决方案--------------------
HTML code

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312" />
        <title></title>
        <style>
            body {
                height:2000px;
            }
            div {
                position:absolute; right:40px; top:40px;
                width:90%; height:30px;
                background:#ddd;
            }
        </style>
    </head>
    <body>
        <div id="test">111111111</div>
        <script>
            function toolbar(el){
                el = typeof el == 'string' ? document.getElementById(el) : el;
                var elTop = el.offsetTop;
                var sTop = 0;
                window.onscroll = function(){
                    sTop = document.body.scrollTop || document.documentElement.scrollTop;
                    if( sTop > elTop ){
                        el.style.top = sTop + 'px';
                    }else{
                        el.style.top = elTop + 'px';
                    }
                }
            }
            toolbar('test');
        </script>
    </body>
</html>

------解决方案--------------------
HTML code
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312" />
        <title></title>
        <style>
            body {
                height:2000px;
            }
            div {
                position:absolute; right:40px; top:40px;
                width:90%; height:30px;
                background:#ddd;
            }
        </style>
    </head>
    <body>
        <div id="test">111111111</div>
        <script>
            function toolbar(el){
                el = typeof el == 'string' ? document.getElementById(el) : el;
                var elTop = el.offsetTop;
                var sTop = 0;
                window.onscroll = function(){
                    sTop = document.body.scrollTop || document.documentElement.scrollTop;
                    if( sTop > elTop ){
                        el.style.position="fixed";
                        el.style.top = 0 + 'px';
                    }else{
                        el.style.position="absolute";
                        el.style.top = elTop + 'px';
                    }
                }
            }
            toolbar('test');
        </script>
    </body>
</html>