萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 返回頂部按鈕完整實現教學

功能需求

  • 頁面滾動超過一定高度時顯示按鈕
  • 點擊平滑滾動至頂部
  • 滑鼠懸停顯示提示、變色
  • IE6 相容定位(可選)
  • 無需外部 CSS,樣式內建

完整程式碼

// 1. 動態建立按鈕 DOM
$("body").append(
    '<div id="toTop" style="display:none; position:fixed; bottom:20px; right:20px; ' +
    'width:40px; height:40px; background:#09F; color:#fff; cursor:pointer; ' +
    'text-align:center; line-height:40px; border-radius:4px; z-index:9999;">' +
    '<span id="toTopTips" style="display:none; position:absolute; left:-60px; top:0; ' +
    'background:#333; color:#fff; padding:2px 6px; border-radius:3px; white-space:nowrap;">' +
    '返回頂部</span>▲</div>'
);

var $toTop = $("#toTop");

// 2. 事件綁定
$toTop.on({
    click: function() {
        $("html, body").animate({ scrollTop: 0 }, 500);
    },
    mouseenter: function() {
        $("#toTopTips").stop(true, true).fadeIn();
        $(this).css("background-color", "#51B9FF");
    },
    mouseleave: function() {
        $("#toTopTips").hide();
        $(this).css("background-color", "#09F");
    }
});

// 3. 滾動監聽
$(window).on("scroll", function() {
    // IE6 降級處理(現代專案可移除)
    if ($.browser.msie && $.browser.version === "6.0" && !$.support.style) {
        $toTop.css({
            top: $(window).scrollTop() + $(window).height() - 100,
            position: "absolute"
        });
    }

    if ($(window).scrollTop() <= 50) {
        $toTop.fadeOut();
    } else {
        $toTop.fadeIn();
    }
});

關鍵點解析

動態建立 DOM

使用 append() 直接注入 HTML 字串,避免需額外引入 CSS 檔案。樣式採用行內 style 確保零依賴。

平滑滾動

$("html, body").animate({ scrollTop: 0 }, 500) 同時針對 html 與 body 動畫,相容各瀏覽器滾動容器差異。

提示顯示優化

.stop(true, true) 防止快速進出導致動畫佇列堆疊,fadeIn()/hide() 控制提示顯隱。

IE6 相容

利用 $.browser 判斷(jQuery 1.9+ 已移除,現代專案建議移除此區塊),將 fixed 定位改為 absolute 並動態計算 top 值。

現代化重構建議

// ES6 + CSS 版本
const createBackToTop = () => {
    const btn = document.createElement("div");
    btn.id = "toTop";
    btn.innerHTML = `<span class="tip">返回頂部</span>▲`;
    document.body.appendChild(btn);

    btn.addEventListener("click", () => {
        window.scrollTo({ top: 0, behavior: "smooth" });
    });

    window.addEventListener("scroll", () => {
        btn.hidden = window.scrollY <= 50;
    });
};

配合 CSS position: fixed、transition、:hover 可完全替代 jQuery 版本,減少依賴。

copyright © 萬盛學電腦網 all rights reserved