现在的位置: 首页 > 综合 > 正文

导航栏滚动到顶部后固定

2014年08月09日 ⁄ 综合 ⁄ 共 889字 ⁄ 字号 评论关闭
<div style="height:500px;background:#999"></div>
<div id="fixedMenu" style="background:#eee;width:100%;">MENU</div>
<div style="height:1900px;background:#999"></div>
<script type="text/javascript" src="http://www.coding123.net/js/jquery.js"></script>
<script type="text/javascript">
    $(function () {
        var ie6 = /msie 6/i.test(navigator.userAgent)
        , dv = $('#fixedMenu'), st;
        dv.attr('otop', dv.offset().top); //存储原来的距离顶部的距离
        $(window).scroll(function () {
            st = Math.max(document.body.scrollTop || document.documentElement.scrollTop);
            if (st >= parseInt(dv.attr('otop'))) {
                if (ie6) {//IE6不支持fixed属性,所以只能靠设置position为absolute和top实现此效果
                    dv.css({ position: 'absolute', top: st });
                }
                else if (dv.css('position') != 'fixed') dv.css({ 'position': 'fixed', top: 0 });
            } else if (dv.css('position') != 'static') dv.css({ 'position': 'static' });
        });
    });
    
</script>

注:http://www.coding123.net/js/jquery.js最好换成本地的js文件:jquery-1.4.2.js,不换的话,当www.coding.net打不开时,引用此域名的网站会出现内容无法加载的情况。

抱歉!评论已关闭.