自動隱藏且可直接使用的網頁回頂部按鈕

2021/11/30 3,844 2 網站技術 , HTML , CSS , JavaScript , jQuery

為了方便以後讓任何網站都能快速擁有回頂部按鈕,特別寫了一個結合 HTML、CSS、JavaScript 和 jQuery 的回頂部按鈕,輕鬆就能使用!基本上只要在網頁 <head> 到 </head> 中先引入 jQuery 後即可直接使用。通常這種設計是為了方便讓使用者在看完網頁主要內容後,能快速回到最上面查看導覽列,若您的網站本身就設有固定於頂部的導覽列,可能就比較不需要這種設計。

接著就讓我們直接來看看原始碼吧!首先是 HTML:

<div class="back-top hide" title="回頂部"></div>

這段只要放在 <body> 到 </body> 中的任何地方即可!再來是 CSS:

.back-top {
  z-index: 99999;
  position: fixed;
  bottom: 5px;
  right: 5px;
  cursor: pointer;
  opacity: 0.5;
  filter: Alpha(opacity=50);
  width: 35px;
  height: 35px;
  background: #000 center no-repeat
    url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3Jn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PSIwIiAvPgo8L2c+CjxnCiAgIGlkPSJnNyI+CjwvZz4KPGcKICAgaWQ9Imc5Ij4KPC9nPgo8ZwogICBpZD0iZzExIj4KPC9nPgo8ZwogICBpZD0iZzEzIj4KPC9nPgo8ZwogICBpZD0iZzE1Ij4KPC9nPgo8ZwogICBpZD0iZzE3Ij4KPC9nPgo8ZwogICBpZD0iZzE5Ij4KPC9nPgo8ZwogICBpZD0iZzIxIj4KPC9nPgo8ZwogICBpZD0iZzIzIj4KPC9nPgo8ZwogICBpZD0iZzI1Ij4KPC9nPgo8ZwogICBpZD0iZzI3Ij4KPC9nPgo8ZwogICBpZD0iZzI5Ij4KPC9nPgo8ZwogICBpZD0iZzMxIj4KPC9nPgo8ZwogICBpZD0iZzMzIj4KPC9nPgo8ZwogICBpZD0iZzM1Ij4KPC9nPgo8L3N2Zz4=);
  background-size: 24px 24px;
  border-radius: 12px;
  border: 1px rgba(255, 255, 255, 0.6) solid;
  box-shadow: 0px 0px 3px #ffffff;
  transform: translateY(0%);
  transition: all 0.2s linear;
}

.back-top:hover {
  opacity: 0.8;
  filter: Alpha(opacity=80);
  box-shadow: 0px 0px 6px #ffffff;
}

.back-top.hide {
  opacity: 0;
  filter: Alpha(opacity=0);
  transform: translateY(150%);
}

我已經將按鈕中的 SVG 向量圖示用 base64 編碼寫入在 CSS 中,另外也設計了動畫效果,讓按鈕更美觀且精緻!最後來看 JavaScript 和 jQuery 的部分:

$(document).ready(function () {
  // 捲軸偵測距離頂部超過 50 才顯示按鈕
  $(window).scroll(function () {
    if ($(window).scrollTop() > 50) {
      if ($(".back-top").hasClass("hide")) {
        $(".back-top").toggleClass("hide");
      }
    } else {
      $(".back-top").addClass("hide");
    }
  });

  // 點擊按鈕回頂部
  $(".back-top").on("click", function (event) {
    $("html, body").animate(
      {
        scrollTop: 0
      },
      500 // 回頂部時間為 500 毫秒
    );
  });
});

透過註解,我已經將兩段程式碼主要做的事情告知給您啦!前面基本上是要讓網頁已經是在最上面時不要顯示出按鈕,後面基本上就是點了按鈕後會花指定的時間滾動到頂部,很容易理解吧!下面有預覽可以直接看~

CodePen

See the Pen
Untitled
by Feng, Cheng-Chi (@qwe987299)
on CodePen.


▲ 精選圖片。

贊助廣告 ‧ Sponsor advertisements

留言區 / Comments

萌芽論壇