图片:
html
<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title>回到顶部</title><link rel="stylesheet" type="text/css" href="css/try.css" /><script src="js/app.js"></script></head><body><div class="box"><img src="img/jkxy.png"/></div><a style="display:none" href="javascript:;" id="btn" title="回到顶部"></a></body>
</html>
css
*{margin: 0;padding: 0;
}
.box {width:1000px;margin: 0 auto;
}
#btn {width:40px;height: 40px;position:fixed;left:50%;bottom:30px;background:url(../img/顶部.png) no-repeat left top ;margin-left: 610px;
}
#btn:hover {background:url(../img/顶部.png) no-repeat left -40px;
}
js
indow.onload = function () {var topbtn = document.getElementById("btn");var timer = null;
//获取屏幕的高度var pagelookheight = document.documentElement.clientHeight;window.onscroll = function(){//滚动超出高度,显示按钮,否则隐藏var backtop = document.body.scrollTop;
// 滚动超过一频 应该显示if(backtop >= pagelookheight){topbtn.style.display = "block";}
// 不显示
else{topbtn.style.display = "none";}}topbtn.onclick = function () {
timer = setInterval(function () {var backtop = document.body.scrollTop;
//速度操作 减速var speedtop = backtop/5; document.body.scrollTop = backtop -speedtop; //高度不断减少if(backtop ==0){ //滑动到顶端clearInterval(timer); //清除计时器}}, 30);}
}
效果: