javascript滚动到导航条时如何固定在顶部
当页面上面的不在第一屏显示的导航条,javascript如何将导航条固定在顶部当次导航条已经显示并且滚动到顶部将隐藏的时候。
下面为这个效果的源代码,为了简便,使用了jquery框架
<div style="height:500px;background:#999"></div> <div id="fixedMenu" style="background:#eee;width:100%;">菜单</div> <div style="height:900px;background:#999"></div> <script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.7.1/jquery.min.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>
加支付宝好友偷能量挖...
原创文章,转载请注明出处:javascript滚动到导航条时如何固定在顶部