demo.js
window.onload=function() {
var timer=null;
var obtn=document.getElementById('btn');
var isTop=true;
window.onscroll=function() {
if(!isTop) {
clearInterval(timer); }
isTop=false;
} obtn.onclick=function () {
timer=setInterval(function(){
var osTop=document.documentElement.scrollTop||document.body.scrollTop;
var ispeed=Math.floor(-osTop/5);
document.documentElement.scrollTop=document.body.scrollTop-=osTop+ispeed;
isTop=true; if(osTop==0) {
clearInterval(timer);
} },30); } }
demo.css
.box {
width:1190px;
margin: 0 auto;
}
#btn {
width:40px;
height: 40px;
position:fixed;
left:50%;
bottom:30px;
background:url(顶部.png) no-repeat left top ;
margin-left: 610px;
}
#btn:hover {
background:url(顶部.png) no-repeat left -40px ;
}
demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>回到顶部</title>
<link rel="stylesheet" type="text/css" href="demo.css">
<script type="text/javascript" src="demo.js"></script>
</head>
<body>
<div class="box">
<img src="背景.jpg"/>
</div>
<a href="javascript:;" id="btn" title="回到顶部"></a>
</body>
</html>
效果: