// ==UserScript== // @name 全局网页回到顶部Top/底部Down // @description 便捷的全局回到顶部/底部按钮(Top and Down buttons everywhere) // @version 2.3 // @author Max Max // @license MIT // @include * // @match https://*.baidu.com/* // @match https://segmentfault.com/* // @match https://*.v2ex.com/* // @match https://hacpai.com/* // @match https://github.com/* // @match https://*.zhihu.com/* // @match https://*.cnblogs.com/* // @match https://*.jianshu.com/* // @match http://*.163.com/* // @run-at document-end // @grant none // @namespace https://greasyfork.org/users/1267557 // @downloadURL none // ==/UserScript== (function () { if (window.self !== window.top) return; // 跳过 iframe // 创建样式 const addStyle = (css) => { const style = document.createElement("style"); style.type = "text/css"; style.appendChild(document.createTextNode(css)); document.head.appendChild(style); }; // 按钮样式 addStyle(` .scroll-btn { position: fixed; right: 10px; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; background: rgba(0, 0, 0, 0.6); color: #fff; font-size: 18px; text-align: center; line-height: 40px; cursor: pointer; border-radius: 5px; z-index: 9999; display: none; transition: opacity 0.3s; } .scroll-btn:hover { background: rgba(0, 0, 0, 0.8); } #scroll-top { margin-top: -25px; } #scroll-bottom { margin-top: 25px; } `); // 创建按钮 const createButton = (id, text) => { const btn = document.createElement("div"); btn.id = id; btn.className = "scroll-btn"; btn.innerHTML = text; document.body.appendChild(btn); return btn; }; const btnTop = createButton("scroll-top", "▲"); const btnBottom = createButton("scroll-bottom", "▼"); // 平滑滚动函数 const smoothScroll = (targetY) => { const startY = window.scrollY; const distance = targetY - startY; const duration = 500; // 动画时长 let startTime; const step = (timestamp) => { if (!startTime) startTime = timestamp; const progress = timestamp - startTime; const ease = progress / duration; window.scrollTo(0, startY + distance * ease); if (progress < duration) { requestAnimationFrame(step); } else { window.scrollTo(0, targetY); } }; requestAnimationFrame(step); }; // 监听滚动,显示/隐藏按钮 const updateButtons = () => { const scrollY = window.scrollY; const maxScroll = document.documentElement.scrollHeight - window.innerHeight; btnTop.style.display = scrollY > 100 ? "block" : "none"; btnBottom.style.display = scrollY < maxScroll - 100 ? "block" : "none"; }; // 绑定点击事件 btnTop.addEventListener("click", () => smoothScroll(0)); btnBottom.addEventListener("click", () => smoothScroll(document.body.scrollHeight)); // 监听滚动事件 window.addEventListener("scroll", updateButtons); // 初始化按钮状态 updateButtons(); })();