實現(xiàn)回到頂部,先快后慢耳高,在回到頂部過程中可以滾動滾輪打斷回到頂部過程。
回到頂部按鈕在第二屏才會出現(xiàn)所踊,回到第一屏消失泌枪。
<!DOCTYPE html>
<!--實現(xiàn)回到頂部,先快后慢秕岛,在回到頂部過程中可以滾動滾輪打斷回到頂部過程碌燕。-->
<!--回到頂部按鈕在第二屏才會出現(xiàn)误证,回到第一屏消失。-->
<html>
<head>
<meta charset="utf-8">
<title>回到頂部實例</title>
</head>
<script type="text/javascript">
window.onload = function(){
var obtn = document.getElementById('btn');
var clientHeight = document.documentElement.clientHeight;
var timer = null;
var isTop = true;
//滾動條滾動時觸發(fā)
window.onscroll=function() {
var osTop = document.documentElement.scrollTop||document.body.scrollTop;
if (osTop>clientHeight) {
obtn.style.display ='block';
}else{
obtn.style.display = 'none';
}
if (!isTop) {
clearInterval(timer);
}
isTop=false;
}
//點擊返回頂部按鈕觸發(fā)
obtn.onclick = function(){
clearInterval(timer);
timer =setInterval(function(){
var osTop = document.documentElement.scrollTop||document.body.scrollTop;
var ispeed = Math.floor(-osTop/7);//對浮點數(shù)向下取整修壕,小于或者等于該參數(shù)的最大整數(shù)愈捅。
document.documentElement.scrollTop = document.body.scrollTop = osTop+ispeed;
isTop=true;
console.log(osTop);
if (osTop==0) {
clearInterval(timer);
}
},30)
}
}
</script>
<style>
body
{
background-color: lightblue;
height: 7001px;
}
a
{
position: fixed;
right: 20px;
bottom: 20px;
display: none;
}
</style>
<body>
<a href="javascript:;" id="btn">回到頂部</a>
</body>
</html>