<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>回到顶部scrollTop</title>
<style type="text/css">
#button{width: 50px;height: 50px;border-radius: 50%;background: #000;opacity: 0.4;position: fixed;bottom: 30px;right: 30px;display: none;}
.content{background:-webkit-gradient(linear, 0 0, 0 100%, from(green), to(yellow));height: 2000px;width: 100%;}
</style>
</head>
<body>
<div id="button"></div>
<div class="content"></div>
<script>
// 回到顶部scrollTop
// 总时间(duration):500ms
//频率(interval):多长时间走一步 10ms
//总距离(target):当前的位置(当前的scrollTop值)目标位置0;
// 步长(step):每一次走的距离 target/duration * interval 每一次走的距离
var button = document.getElementById("button");
window.onscroll = computedDisplay;
function computedDisplay(){
var curTop = document.documentElement.scrollTop || document.body.scrollTop;
var curHeight = document.documentElement.clientHeight || document.body.clientHeight;
button.style.display = curTop>curHeight?"block":"none";
}
button.onclick = function(){
this.style.display = "none";
window.onscroll = null;
var duration = 500,interval = 10,target = document.documentElement.scrollTop || document.body.scrollTop;
var step = (target/duration) * interval;
var timer = window.setInterval(function(){
var curTop = document.documentElement.scrollTop || document.body.scrollTop;
if(curTop ===0){
window.clearInterval(timer);
window.onscroll = computedDisplay;//动画结束后方法重新绑定
return;
}
curTop -=step;
document.documentElement.scrollTop = curTop;
document.body.scrollTop = curTop;
},interval);
}
</script>
</body>
</html>
网友评论