导航栏滚动到顶部后固定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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打不开时,引用此域名的网站会出现内容无法加载的情况。