jQuery滚动页面当DIV到达顶部时固定在顶部,到底部是固定在底部

1955 查看

jQuery滚动页面当DIV到达顶部时固定在顶部,到底部是固定在底部
可以做类似美团网右侧的浏览记录效果
直接上代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery滚动页面当DIV到达顶部时固定在顶部,到底部是固定在底部</title>
</head>
<style>
body{margin:0; padding:0; background:#fff}
div{width:100%;}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<body>
<div style="height:100px;background:#999"></div>
<div style="height:200px;">
<div id="menu" style="background:green; height:200px;"></div>
</div>
<div style="height:200px;"></div>
<div id="bottom" style="background:red; height:200px; margin-top:100px;"></div>
<div style="height:800px;background:#999"></div>
<script type="text/javascript">
$(function () {
var ie6 = document.all;
var dv = $('#menu'), st, botv;
var bv = $('#bottom');
dv.attr('otop', dv.offset().top);
dv.attr('oheight', dv.height());

$(window).scroll(function () {
st = Math.max(document.body.scrollTop || document.documentElement.scrollTop);
botv=bv.offset().top-st-parseInt(dv.attr('oheight'));
if (st > parseInt(dv.attr('otop'))) {
if(parseInt(bv.offset().top-st)<parseInt(dv.attr('oheight'))){
dv.css({ 'position': 'fixed', top: botv });
}else{
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>
</body>
</html>