<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>回到顶部</title>
<style>
.bg{
width: 1190px;
margin: 0 auto;
}
#btn{
width: 40px;
height: 40px;
position: fixed;
right: 65px;
bottom: 10px;
background: url(images/top_bg.png) no-repeat 0 0 ;
display: none;
}
#btn:hover{
background-position: 0 -39px;
}
</style>
</head>
<body>
<a href="javascript:;" id="btn" title="回到顶部"></a>
<div class="bg">
<img src="images/tb_bg.jpg" alt="bg"/>
</div>
<script>
window.onload = function(){
var oBtn = document.getElementById(‘btn‘);
// 获取屏幕可视高度
var oHeight = document.documentElement.clientHeight;
var timer = null;
// 一开始就要把myTop设为ture,不然会一开始就执行window.onscroll 的函数
var myTop = true;
oBtn.onclick = function(){
// 获取被卷上去的高度document.documentElement和document.body是为了兼容
// var oTop = document.documentElement.scrollTop || document.body.scrollTop;
// alert(oTop);
// 指点跳到页面总高度的600px的位置
// document.documentElement.scrollTop = document.body.scrollTop = 600;
//每次点击往上跳200px
// document.documentElement.scrollTop = document.body.scrollTop -= 200;
timer = setInterval(function(){
var oTop = document.documentElement.scrollTop || document.body.scrollTop;
// 向上取整,比如0.5会取整为1
var iSpeed = Math.ceil(oTop/5);
// 每次都把myTop设为ture,才不会一直卡
myTop = true;
document.documentElement.scrollTop = document.body.scrollTop = oTop - iSpeed;
oTop == 0 && clearInterval(timer);
},30);
}
window.onscroll = function(){
var oTop = document.documentElement.scrollTop || document.body.scrollTop;
// 控制按钮的显示与隐藏
if(oTop >= oHeight){
oBtn.style.display = ‘block‘;
}else{
oBtn.style.display = ‘none‘;
}
// myTop为false才会执行
if(!myTop){
clearInterval(timer);
}
// 每次都要把myTop 设为 false,因为timer循环每次都把myTop设为ture
myTop = false;
}
}
</script>
</body>
</html>