標籤:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>回到頂部</title>
<style>
body{
height:1600px;
}
.top{
width:100%;
height: 30px;
background:red;
}
#box{
width:100px;
height:30px;
background: pink;
line-height: 30px;
position: fixed; -->這裡注意使用固定定位。
top:90%;
right:40px;
display: none; -->開始時將回到頂部的按鈕設定為隱藏屬性,當可視地區高度距離頁面頂部(scrolltop)的距離達到一定值時,通過改變dispaly 使其顯示。
cursor: pointer;
}
</style>
<script>
window.onload = function(){
var box = document.getElementById("box");
var top = 0;
var timer;
window.onscroll = function(){
top = document.documentElement.scrollTop || document.body.scrollTop;
if(top > 600){
box.style.display = "block";
}else{
box.style.display = "none";
}
}
box.onclick = function(){
clearInterval(timer);
var sudu = 10;
timer = setInterval(function(){
//console.log(top); ----->注意測試top值,以免發生計時器未清除的情況。
if(top <= 0){
clearInterval(timer);
}else{
document.documentElement.scrollTop = document.body.scrollTop = top - sudu;
}
},10);
}
}
</script>
</head>
<body>
<div class="top"></div>
<div id="box">
點我回到頂部
</div>
</body>
</html>
js實現簡單的勻速回到頁面頂部。