欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實(shí)現(xiàn)返回頂部按鈕案例

 更新時(shí)間:2021年11月07日 16:03:29   作者:小白小白從不日白  
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)返回頂部按鈕案例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了JavaScript實(shí)現(xiàn)返回頂部按鈕的具體代碼,供大家參考,具體內(nèi)容如下

思路:

首先先設(shè)計(jì)出其靜態(tài)樣式,這里主要利用固定定位,將其固定在頁(yè)面底部的某一位置處

.backtotop {
    position: fixed;
    bottom: 80px;
    right: 80px;
    width: 80px;
    height: 80px;
    background-color: #ccc;
    font-size: 20px;
    text-align: center;
    padding-top: 12px;
    box-sizing: border-box;
    cursor: pointer;
    color: #000;
    /* 先隱藏按鈕 */
    display: none;
  }

其次就是設(shè)計(jì)邏輯部分:當(dāng)鼠標(biāo)點(diǎn)擊“返回頂部”按鈕時(shí),則會(huì)以每20毫秒的周期以一定“速度”返回到頂部,回到頂部之后則要進(jìn)行清除,否則將出現(xiàn)只要一往下拉頁(yè)面就會(huì)自動(dòng)返回頂部的現(xiàn)象;在這里就要用到兩個(gè)方法一個(gè)是 setInterval,一個(gè)是clearInterval,前者是設(shè)置定時(shí)器,后者為清除定時(shí)器。

在這里要注意一點(diǎn)的是,為了不引起沖突,在設(shè)置定時(shí)器之前要進(jìn)行“設(shè)表先關(guān)”

最后為了增加用戶(hù)的體驗(yàn)感,我們需要設(shè)計(jì)成,當(dāng)前如果是在頂部時(shí),那么“返回頂部”按鈕就會(huì)自動(dòng)隱藏;當(dāng)前如果不在頂部時(shí),“返回頂部”按鈕就顯示

最后我們來(lái)看一下完整的案例:

<a href="javascript:;" class="backtotop" id="backtotop">返回<br>頂部</a>
a {
    text-decoration: none;
  }

  body {
    height: 5000px;
  }

  .backtotop {
    position: fixed;
    bottom: 80px;
    right: 80px;
    width: 80px;
    height: 80px;
    background-color: #ccc;
    font-size: 20px;
    text-align: center;
    padding-top: 12px;
    box-sizing: border-box;
    cursor: pointer;
    color: #000;
    /* 先隱藏按鈕 */
    display: none;
}
<script>
(function(){
  //獲得元素
  var backtotop = document.getElementById('backtotop');

  var timer;
  backtotop.onclick = function(){
    //設(shè)表先關(guān),防止定時(shí)器沖突
    clearInterval(timer);

    //設(shè)置定時(shí)器
    timer = setInterval(function(){

      // 更改根元素的scrollTop元素值
      //兼容性問(wèn)題
      var top = document.documentElement.scrollTop || document.body.scrollTop;
      top = top - 80;
      document.documentElement.scrollTop = top;
      document.body.scrollTop = top;

      //判斷
      if(top <= 0) {
        //關(guān)閉定時(shí)器
        clearInterval(timer);
      }
    },20);
  };

  //監(jiān)聽(tīng)頁(yè)面滾動(dòng)
  window.onscroll = function() {
    //得到卷動(dòng)值
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop || window.scrollY;

    //當(dāng)頁(yè)面沒(méi)有卷動(dòng)時(shí),返回頂部 按鈕就隱藏
    if(scrollTop == 0) {
      backtotop.style.display = 'none';
    }else {
        backtotop.style.display = 'block';
    }
  };
})();

<script>

當(dāng)頁(yè)面沒(méi)有發(fā)生卷動(dòng)時(shí):

當(dāng)頁(yè)面發(fā)生卷動(dòng)時(shí):

最后感興趣的小伙伴可以親自動(dòng)手去試試!

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論