這篇文章主要介紹了基于JavaScript實(shí)現(xiàn)回到頁(yè)面頂部動(dòng)畫(huà)代碼的相關(guān)資料,代碼簡(jiǎn)單易用,非常實(shí)用,需要的朋友可以參考下
最近做的都是前端的項(xiàng)目,很多項(xiàng)目都有回到頂部的需求,下面把我寫(xiě)js代碼做個(gè)筆錄,方便以后查找。
發(fā)現(xiàn)還可以添加從快到慢的動(dòng)畫(huà)效果和隨時(shí)下拉滾動(dòng)條停止?jié)L動(dòng)的功能, 參考了imooc上相關(guān)課程,最終實(shí)現(xiàn)JS代碼如下:
//頁(yè)面加載后觸發(fā)
window.onload = function(){
var btn = document.getElementById('btn');
var timer = null;
var isTop = true;
//獲取頁(yè)面可視區(qū)高度
var clientHeight = document.documentElement.clientHeight;
//滾動(dòng)條滾動(dòng)時(shí)觸發(fā)
window.onscroll = function() {
//顯示回到頂部按鈕
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
if (osTop >= clientHeight) {
btn.style.display = "block";
} else {
btn.style.display = "none";
};
//回到頂部過(guò)程中用戶(hù)滾動(dòng)滾動(dòng)條,停止定時(shí)器
if (!isTop) {
clearInterval(timer);
};
isTop = false;
};
btn.onclick = function() {
//設(shè)置定時(shí)器
timer = setInterval(function(){
//獲取滾動(dòng)條距離頂部高度
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var ispeed = Math.floor(-osTop / 7);
document.documentElement.scrollTop = document.body.scrollTop = osTop+ispeed;
//到達(dá)頂部,清除定時(shí)器
if (osTop == 0) {
clearInterval(timer);
};
isTop = true;
},30);
};
};
以上內(nèi)容是小編給大家介紹的基于JavaScript實(shí)現(xiàn)回到頁(yè)面頂部動(dòng)畫(huà)代碼,代碼簡(jiǎn)單易懂,所有沒(méi)給大家附太多的注釋