Greasy Fork is available in English.
滑动到顶部、底部按钮
// ==UserScript==
// @name 滑动按钮
// @namespace http://tampermonkey.net/
// @version 2026-02-10
// @description 滑动到顶部、底部按钮
// @author encounterxh
// @license MIT
// @match *://*/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=google.com
// @grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
function toTopOrBottomButton() {
// 1. 添加按钮样式
GM_addStyle(`
#toTopBtn, #toBottomBtn {
position: fixed;
top: 90px;
right: 20px;
z-index: 9999;
width: 40px;
height: 40px;
cursor: pointer;
background: #333;
color: #fff;
border: none;
border-radius: 50%;
opacity: 0.7;
transition: opacity 0.3s;
}
#toTopBtn { bottom: 40px; }
#toTopBtn:hover, #toBottomBtn:hover { opacity: 1; }
.btn-hidden { opacity: 0 !important; pointer-events: none !important; }
`);
// 2. 创建按钮并添加到页面
const toTopBtn = document.createElement("button");
const toBottomBtn = document.createElement("button");
toTopBtn.id = "toTopBtn";
toBottomBtn.id = "toBottomBtn";
toTopBtn.textContent = "↑";
toBottomBtn.textContent = "↓";
document.body.appendChild(toTopBtn);
document.body.appendChild(toBottomBtn);
// 3. 滚动监听显示/隐藏按钮
window.addEventListener("scroll", () => {
const scrollY = window.scrollY;
toTopBtn.classList.toggle("btn-hidden", scrollY < 200);
toBottomBtn.classList.toggle(
"btn-hidden",
scrollY > document.body.scrollHeight - window.innerHeight - 200
);
});
// 4. 点击事件(适配自定义容器)
const getScrollContainer = () => {
return document.querySelector(".scroll-container") || window;
};
toTopBtn.addEventListener("click", () => {
const container = getScrollContainer();
container.scrollTo({ top: 0, behavior: "smooth" });
});
toBottomBtn.addEventListener("click", () => {
const container = getScrollContainer();
const scrollHeight = container.scrollHeight || document.body.scrollHeight;
container.scrollTo({ top: scrollHeight, behavior: "smooth" });
});
// 初始化隐藏按钮
toTopBtn.classList.add("btn-hidden");
}
function executeJobAfterRender() {
document.addEventListener("DOMContentLoaded", function () {
setTimeout(function () {
toTopOrBottomButton();
}, 1000);
});
// 兜底:如果DOMContentLoaded已触发,直接延时执行
if (
document.readyState === "complete" ||
document.readyState === "interactive"
) {
setTimeout(toTopOrBottomButton, 1000);
}
}
executeJobAfterRender();
})();