溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JavaScript如何實現(xiàn)網(wǎng)頁帶動畫返回頂部

發(fā)布時間:2022-08-11 11:52:14 來源:億速云 閱讀:194 作者:iii 欄目:開發(fā)技術(shù)

這篇“JavaScript如何實現(xiàn)網(wǎng)頁帶動畫返回頂部”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“JavaScript如何實現(xiàn)網(wǎng)頁帶動畫返回頂部”文章吧。

第一個版本:

<body >
    <div id="topAnchor"></div>
    <a href="#topAnchor" rel="external nofollow"  >回到頂部</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://cache.yisu.com/upload/information/20220811/112/12660.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(){
                // 設(shè)置定時器
                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文件中可以直接運行。

代碼具體含義其中基本都有注釋。

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

方法補充

其實實現(xiàn)返回頂部效果的方法有很多,除了上文的方法,小編也為大家整理一些其他方法,感興趣的可以嘗試下

方法一

//頁面加載后觸發(fā)
window.onload = function(){
  var btn = document.getElementById('btn');
  var timer = null;
  var isTop = true;
  //獲取頁面可視區(qū)高度
  var clientHeight = document.documentElement.clientHeight;

  
  //滾動條滾動時觸發(fā)
  window.onscroll = function() {
  //顯示回到頂部按鈕
    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (osTop >= clientHeight) {
      btn.style.display = "block";
    } else {
      btn.style.display = "none";
    };
  //回到頂部過程中用戶滾動滾動條,停止定時器
    if (!isTop) {
      clearInterval(timer);
    };
    isTop = false;

  };

  btn.onclick = function() {
    //設(shè)置定時器
    timer = setInterval(function(){
      //獲取滾動條距離頂部高度
      var osTop = document.documentElement.scrollTop || document.body.scrollTop;
      var ispeed = Math.floor(-osTop / 7);
      
      document.documentElement.scrollTop = document.body.scrollTop = osTop+ispeed;
      //到達頂部,清除定時器
      if (osTop == 0) {
        clearInterval(timer);
      };
      isTop = true;
      
    },30);
  };
};

方法二

<!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>返回頂部效果</title>
     <style>
         .slider-bar {
             position: absolute;
             left: 47%;
             top: 300px;
             margin-left: 600px;
              45px;
             height: 130px;
             background-color: pink;
             cursor: pointer;
         }
         .w {
              1100px;
             margin: 10px auto;
         }
         .header {
             height: 150px;
             background-color: purple;
         }
         .banner {
             height: 250px;
             background-color: skyblue;
         }
         .main {
             height: 1000px;
             background-color: yellowgreen;
         }
         span {
             display: none;
             position: absolute;
             bottom: 0;
         }
     </style>
 </head>
 <body>
     <div class="slider-bar">
         <span class="goBack">返回頂部</span>
     </div>
     <div class="header w">頭部區(qū)域</div>
     <div class="banner w">banner區(qū)域</div>
     <div class="main w">主體部分</div>
 
     <script>
         // querySelector() 方法返回匹配指定選擇器()的第一個元素,傳的必須是字符串
         var sliderbar = document.querySelector('.slider-bar');
         var banner = document.querySelector('.banner');
         var bannerTop = banner.offsetTop; // banner模塊距離頂部的長度
         var sliderbarTop = sliderbar.offsetTop - bannerTop; // 側(cè)邊欄固定后距離頂部的長度
 
         var main = document.querySelector('.main');
         var goBack = document.querySelector('.goBack');
         var mainTop = main.offsetTop;  // main模塊距離頂部的長度
         
         // scroll 屏幕發(fā)生滾動事件時執(zhí)行
         document.addEventListener('scroll', function() {
             if(window.pageYOffset >= bannerTop) {    // window.pageYOffset 屏幕被滾上去的距離
                 sliderbar.style.position = 'fixed';   // 當用戶滾到banner模塊時使側(cè)邊欄變?yōu)楣潭顟B(tài)
                 sliderbar.style.top = sliderbarTop + 'px'; 
             } else {
                 sliderbar.style.position = 'absolute';
                 sliderbar.style.top = '300px';
             }
             
             if(window.pageYOffset >= mainTop) {    // 當用戶滾到main模塊時顯示返回頂部按鈕
                 goBack.style.display = 'block';
             } else {
                 goBack.style.display = 'none';
             }
             
         });
         sliderbar.addEventListener('click', function() {
             animate(window, 0);
         })
 
         /* 動畫函數(shù):
          *  obj 做動畫的對象(這里就是指window)
          *  target 目標位置(頂部)
          *  callback 回調(diào)函數(shù)(沒有傳參的話就不執(zhí)行)
          */
         function animate(obj, target, callback) {
             clearInterval(obj.timer);  // 先清除定時器,保證只有一個定時器在執(zhí)行,以免出現(xiàn)bug
             obj.timer = setInterval(function() {
                 // window.pageYOffset距離頂部的距離(是負的)
                 var step = (target - window.pageYOffset) / 10;  // step步長(讓頁面速度逐漸變慢的滑動上去)
                 step = step > 0 ? Math.ceil(step) : Math.floor(step); // step并不總是整數(shù)。大于零向上取整,小于零向下取整
                 if(window.pageYOffset == target) {  // 當頁面回到頂部后(即動畫執(zhí)行完) 清除定時器
                     clearInterval(obj.timer);
                     //  判斷是否傳了回調(diào)函數(shù)
                     /* if(callback) { 
                         callback();
                     } */
                     // 可以簡寫為下邊這種。 &&是短路運算符,存在callback(即第一個式子為true)時才會繼續(xù)執(zhí)行callback()
                     callback && callback();
                 }
                 // window.scroll(x, y) 滾動到文檔特定位置
                 window.scroll(0, window.pageYOffset + step);
             }, 15);
         }
     </script>
 </body>
 </html>

以上就是關(guān)于“JavaScript如何實現(xiàn)網(wǎng)頁帶動畫返回頂部”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI