<!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>
<title>无标题页</title>
<script src="../js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var timer = null;
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
var divObj = $("#tv");
var divHeight = divObj.height();
var clientHeight = $(window).height();
var targetTop = parseInt(scrollTop +(clientHeight-divHeight)/2);
divObj.css("top",targetTop+"px");
clearInterval(timer);
timer = setInterval(function(){
var top = divObj.offset().top;
var speed = (targetTop - top)/6;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
var target = top + speed;
if(Math.abs(target-targetTop)<6)
{
clearInterval(timer);
divObj.css("top",targetTop+"px");
}
else
{
divObj.animate({ top: "+="+speed }, 1000);
}
},30);
});
</script>
</head>
<body style="height:2000px">
<input type="text" id="txt" style="position:fixed;width:300px" />
<div id="tv" style="position:absolute;width:200px;height:200px;right:0px;border:1px solid red"></div>
</body>
</html>
w3c scroll事件:
http://www.w3school.com.cn/tiy/t.asp?f=jquery_event_scroll