<!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" xml:lang="en">
<head>
<title>Javascript 回到顶部效果</title>
<style rel="stylesheet" type="text/css">
#btn {
width:40px;
height:40px;
position:fixed;
left:50%;
display:none;
margin-left:610px;
bottom:30px;
background:url(http://img1.sycdn.imooc.com//535e0dc100010e9c00400080.jpg) no-repeat left top;
}
#btn:hover
{
background:url(http://img1.sycdn.imooc.com//535e0dc100010e9c00400080.jpg) no-repeat 0 -39px;
}
.box
{
width:1190px;
margin:0 auto;
}
</style>
<script type="text/javascript" >
window.onload = function()
{
var obtn = document.getElementById('btn');
//获取可视页面的高度
var clientHeight = document.documentElement.clientHeight;
var timer = null;
var isTop = true;
obtn.onclick = function()
{
//设置定时器
timer = setInterval(function()
{
//获取滚动条距离顶部的距离
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
if(osTop >= clientHeight)
{
obtn.style.display = "block";
}
else
{
obtn.style.display = "none";
}
if(!isTop)
{
clearInterval(timer);
}
isTop = false;
var ispeed = Math.floor(-osTop / 6);
document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
isTop = true
console.log(osTop - ispeed);
if(osTop == 0)
{
clearInterval(timer);
}
},30);
}
}
</script>
</head>
<body>
<div>
<img src="http://img1.sycdn.imooc.com//535e0ce800015b7511902787.jpg" />
</div>
<a href="javascript:;" id="btn" title="回到顶部"></a>
</body>
</html>