// ==UserScript== // @name 回到顶部(长按置底) // @version 1.0.4.2 // @description 支持在所有页面生成一个顺滑回到顶部的按钮,修改自https://greasyfork.org/zh-CN/scripts/435303-%E5%9B%9E%E5%88%B0%E9%A1%B6%E9%83%A8 // @author @leo // @email ygnh136@qq.com // @match *://*/* // @license MIT // @namespace https://greasyfork.org/zh-CN/users/954189 // @downloadURL none // ==/UserScript== ;(() => { //注入CSS var style = document.createElement('style'); style.innerHTML = ` .GO_TO_TOP_button { width: 42px; height: 42px; border-radius: 8px; box-shadow: 0 3px 6px rgb(0 0 0 / 16%), 0 1px 2px rgb(0 0 0 / 23%); position: fixed; left: 50%; transform: translate(-50%,0); bottom: 15px; display: flex; align-items: center; justify-content: center; z-index: 99999999; background-color: white; opacity: 0.5; } .GO_TO_TOP_button svg { width: 24px; height: 24px; margin: 0; } `; document.head.appendChild(style); // 创建页面回到顶/底部方法 const goToTop = () => { window.scrollTo(0, 0); } const goToBottom = () => { window.scrollTo(0,document.body.scrollHeight); } // 创建DOM绑定方法 const button = document.createElement('div') button.className = 'GO_TO_TOP_button' button.innerHTML = '' //长按0.5秒直达底部,不足0.5秒直达顶部 let pressTimer; let isLongPress = false; button.addEventListener("touchstart", (event) => { event.preventDefault(); pressTimer = setTimeout(() => { isLongPress = true; goToBottom(); }, 500); }); button.addEventListener("touchend", (event) => { event.preventDefault(); clearTimeout(pressTimer); if (!isLongPress) { goToTop(); } isLongPress = false; }); // 默认隐藏按钮 button.style.display = 'none' document.body.appendChild(button) //不在顶部时显示按钮,静止2秒后隐藏按钮 let timer; window.addEventListener('scroll', function() { clearTimeout(timer); button.style.display = window.pageYOffset > 50 ? 'flex' : 'none'; timer = setTimeout(() => { button.style.display = 'none'; }, 2000); }); // 监听滚动并渲染节点 document.addEventListener('scroll', onScroll) })()