jQuery---小火箭返回頂部案例

小火箭返回頂部案例

 

1. 滾動頁面,當頁面距離頂部超出1000px,顯示小火箭。javascript

封裝在scroll函數裏,當前頁面距離頂部爲$(window).scrollTop >=1000html

小火箭顯示和隱藏用fadeIn和fadeOutjava

 

      //當頁面超出1000px的時候,讓小火箭顯示,若是小於1000px,則隱藏
      $(window).scroll(function () {
        if ($(window).scrollTop() >= 1000) {
          $(".actGotop").stop().fadeIn(1000);
        } else {
          $(".actGotop").stop().fadeOut(1000);
        }
      })
    });

 

2. 當小火箭出現後,點擊小火箭,返回到頁面頂部。jquery

在外面出冊點擊事件,獲取頁面,html或者body, 返回用animate動畫函數,到頂部即scrollTop爲0,時間能夠設置函數

    $(".actGotop").click(function () {
      $("html,body").stop().animate({ scrollTop: 0 }, 1000);
    });

 

3. 若是要讓小火箭點擊後,直接回到頂部,能夠只設置$(window).scrollTop(0),既可動畫

    $(".actGotop").click(function () {
      //$("html,body").stop().animate({ scrollTop: 0 }, 1000);
      //scrollTop爲0
      $(window).scrollTop(0);
    });

 

 

總體代碼以下:url

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    body {
      height: 8000px;
    }

    a {
      color: #FFF;
    }

    .actGotop {
      position: fixed;
      bottom: 50px;
      right: 50px;
      width: 150px;
      height: 195px;
      display: none;
      z-index: 100;
    }

    .actGotop a,
    .actGotop a:link {
      width: 150px;
      height: 195px;
      display: inline-block;
      background: url(images/gotop.png) no-repeat;
      outline: none;
    }

    .actGotop a:hover {
      width: 150px;
      height: 195px;
      background: url(images/gotop.gif) no-repeat;
      outline: none;
    }
  </style>


</head>

<body>
  <!-- 返回頂部小火箭 -->
  <div class="actGotop"><a href="javascript:;" title="Top"></a></div>


  <script src="jquery-1.12.4.js"></script>
  <script>


    $(function () {
      //當頁面超出1000px的時候,讓小火箭顯示,若是小於1000px,則隱藏
      $(window).scroll(function () {
        if ($(window).scrollTop() >= 1000) {
          $(".actGotop").stop().fadeIn(500);
        } else {
          $(".actGotop").stop().fadeOut(500);
        }
      })
    });

    //在外面註冊
    $(".actGotop").click(function () {
      $("html,body").stop().animate({ scrollTop: 0 }, 1000);
      //scrollTop爲0
      // $(window).scrollTop(0);
    });
  </script>
</body>

</html>
相關文章
相關標籤/搜索