<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
right: 0;
top: 0;
}
</style>
<script>
window.onload=function(){
var oDiv=document.getElementById("div1");
var iTimer=null;
var b=0;
setTop();
window.onscroll=function(){
setTop();
if(b!=1){
//如果b=1,那么当前的scroll事件是被定时器所触发,如果不等于1,那么就是非定时器的其他任何一个操作触发该事件
clearInterval(iTimer);
}
}
oDiv.onclick=function(){
clearInterval(iTimer);
var iCur=iSpeed=0;
iTimer=setInterval(function(){
iCur=document.documentElement.scrollTop || document.body.scrollTop;
iSpeed=Math.floor((0-iCur)/8);
if(iCur==0){
clearInterval(iTimer);
}else{
document.documentElement.scrollTop=document.body.scrollTop=iCur+iSpeed;
}
document.title+=1;
b=1;
},30)
}
function setTop(){
// 滚动条滚动的高
var scrollTop=document.documentElement.scrollTop || document.body.scrollTop;
// 滚动条滚动的高+可视区的高-自身的高
oDiv.style.top=scrollTop+document.documentElement.clientHeight - oDiv.offsetHeight + "px";
}
}
</script>
</head>
<body style="height: 2000px;">
<div id="div1"></div>
</body>
</html>