document.documentElement.scrollTop获取当前页面的滚动条纵坐标
document.body.scrollTop恒为0需要用document.documentElement.scrollTop
代替,IE5.5之后已经不支持document.body.scrollX对象
document.body.clientHeight ==> BODY对象高度
document.documentElement.clientHeight ==> 可见区域高度
HTML代码
<!DOCTYPE html>
<html>
<head>
<title>domScroll.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
#div1{width:60px;height:100px;background-color:#EEE;position: absolute;right: 0;bottom:0;border:1px solid red;border-radius:5px;line-height:100px;font-size:18px;text-align:center;}
</style>
<script type="text/javascript" src="../js/domScroll.js"></script>
</head>
<body style="height:2000px;">
<div id="div1">Scroll</div>
</body>
</html>
js代码
window.onscroll = function(){
var odiv = document.getElementById('div1');
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
//startMove(document.documentElement.clientHeight - odiv.offsetHeight+scrollTop);页面右下角悬浮
startMove(parseInt((document.documentElement.clientHeight - odiv.offsetHeight)/2)+scrollTop);//页面中间悬浮
}
var timer = null;
function startMove(iTarget){
var odiv = document.getElementById('div1');
clearInterval(timer);
timer = setInterval(function(){
var speed = (iTarget - odiv.offsetTop)/4;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(odiv.offsetTop == iTarget){
clearInterval(timer);
}else{
odiv.style.top = odiv.offsetTop+speed+"px";
}
},30);
}