// 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();
}
});
使用 append() 直接注入 HTML 字串,避免需額外引入 CSS 檔案。樣式採用行內 style 確保零依賴。
$("html, body").animate({ scrollTop: 0 }, 500) 同時針對 html 與 body 動畫,相容各瀏覽器滾動容器差異。
.stop(true, true) 防止快速進出導致動畫佇列堆疊,fadeIn()/hide() 控制提示顯隱。
利用 $.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 版本,減少依賴。