<html>
<head>
<meta charset="utf-8">
<style type="text/css">
body,div,span{margin:0;padding: 0}
#div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
right: 3px;
}
</style>
</head>
<body style="height:2000px">
<div id="div1"></div>
<script type="text/javascript">
var div = document.getElementById('div1');
//先让div居中显示
//div.style.top = (document.body.clientHeight-div.offsetHeight)/2 + 'px';
document.body.onscroll = function(){
//document.title = document.body.scrollTop; //获得滚动条滚动的高度
//滚动条滚动之后还想让div居中显示的话,在加上滚动条滚动的高度
//div.style.top = document.body.scrollTop+ (document.body.clientHeight-div.offsetHeight)/2 +'px';
var mudidi = document.body.scrollTop+ (document.body.clientHeight-div.offsetHeight)/2;
startMove(mudidi);
}
var timer = null;
function startMove(mudidi){
var div = document.getElementById('div1');
clearInterval(timer);
timer = setInterval(function(){
if(div.offsetLeft>mudidi){
var speed = (mudidi-div.offsetTop)/10; //-60
speed = Math.floor(speed); //多减一点
}else{
var speed = (mudidi-div.offsetTop)/10; //-60
speed = Math.ceil(speed); //多加一点
}
if(div.offsetTop==mudidi){
clearInterval(timer);
}else{
div.style.top = div.offsetTop + speed +'px';
}
//document.title = "位置:"+div.offsetLeft+'speed:'+speed;
}, 50)
}
</script>
</body>
</html>
<head>
<meta charset="utf-8">
<style type="text/css">
body,div,span{margin:0;padding: 0}
#div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
right: 3px;
}
</style>
</head>
<body style="height:2000px">
<div id="div1"></div>
<script type="text/javascript">
var div = document.getElementById('div1');
//先让div居中显示
//div.style.top = (document.body.clientHeight-div.offsetHeight)/2 + 'px';
document.body.onscroll = function(){
//document.title = document.body.scrollTop; //获得滚动条滚动的高度
//滚动条滚动之后还想让div居中显示的话,在加上滚动条滚动的高度
//div.style.top = document.body.scrollTop+ (document.body.clientHeight-div.offsetHeight)/2 +'px';
var mudidi = document.body.scrollTop+ (document.body.clientHeight-div.offsetHeight)/2;
startMove(mudidi);
}
var timer = null;
function startMove(mudidi){
var div = document.getElementById('div1');
clearInterval(timer);
timer = setInterval(function(){
if(div.offsetLeft>mudidi){
var speed = (mudidi-div.offsetTop)/10; //-60
speed = Math.floor(speed); //多减一点
}else{
var speed = (mudidi-div.offsetTop)/10; //-60
speed = Math.ceil(speed); //多加一点
}
if(div.offsetTop==mudidi){
clearInterval(timer);
}else{
div.style.top = div.offsetTop + speed +'px';
}
//document.title = "位置:"+div.offsetLeft+'speed:'+speed;
}, 50)
}
</script>
</body>
</html>