1. 程式人生 > 其它 >JavaScript實現網頁帶動畫返回頂部

JavaScript實現網頁帶動畫返回頂部

技術標籤:javascripthtmljscssweb

伺服器由阿里雲換到了騰訊雲,我的程式碼之前一直都是託管在git上的,但是搬家的時候,可能是著急了,之前有些新加的檔案沒有託管到git上,所以,就丟了。

不過無所謂了,可以重新寫嘛。

之前部落格的回到頂部功能是請之前的一位前端的同事幫忙寫的,這次打算自己嘗試一下。

返回頂部無非就是錨點。

第一個版本:

<body style="height:2000px;">
    <div id="topAnchor"></div>
    <a href="#topAnchor"
style="position:fixed;right:0;bottom:0">
回到頂部</a> </body>

這個沒用js,單純的使用錨點試了一下,好用。

好用是好用,但是使用者體驗不是很好,嗖的一下就回到頂部了。不好。

我不太喜歡使用jquery,不管坐什麼都喜歡用原生,所以,我這裡用原生JavaScript寫了一個帶動畫的,大概是這樣。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title
>
返回頂部</title> <style type="text/css"> *{ margin: 0; padding: 0; } body{ height: 2000px; width: 100%; } .to_top{ width: 60px; height: 60px; bottom: 10%; right
: 20px; font-size: 40px; line-height: 70px; border: none; background: rgba(0,0,0,0.2); cursor: pointer; opacity: 0; transition: all 1s; /*使點前標籤始終置於最上層*/ position: fixed; z-index: 99999; }
</style> </head> <body> <div class="to_top"> <img src="https://guanchao.site/uploads/gotop/timg.jpg" alt="" width="70;"> </div> <script type="text/javascript"> window.onscroll = function(){ var timer = null;//時間識別符號 var isTop = true; var obtn = document.getElementsByClassName('to_top')[0]; obtn.onclick = function(){ // 設定定時器 timer = setInterval(function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; //減小的速度 var isSpeed = Math.floor(-osTop/6); document.documentElement.scrollTop = document.body.scrollTop = osTop+isSpeed; //判斷,然後清除定時器 if (osTop == 0) { clearInterval(timer); } isTop = true;//新增在obtn.onclick事件的timer中 },30); }; //獲取頁面的可視視窗高度 var client_height = document.documentElement.clientHeight || document.body.clientHeight; //在滾動的時候增加判斷,忘了的話很容易出錯 var osTop = document.documentElement.scrollTop || document.body.scrollTop; if (osTop >= client_height) { obtn.style.opacity = '1'; }else{ obtn.style.opacity = '0'; } if(!isTop){ clearInterval(timer); } isTop = false; } </script> </body> </html>

以上程式碼可以放到html檔案中直接執行。

程式碼具體含義其中基本都有註釋。

有看不懂的地方,請自行百度。

有好的建議,請在下方輸入你的評論。

歡迎訪問個人部落格
https://guanchao.site

歡迎訪問小程式:
在這裡插入圖片描述