便捷的全局回到顶部/底部按钮(Top and Down buttons everywhere)
当前为
// ==UserScript==
// @name 全局网页回到顶部Top/底部Down
// @description 便捷的全局回到顶部/底部按钮(Top and Down buttons everywhere)
// @version 2.5
// @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://gf.qytechs.cn/users/1267557
// ==/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;
opacity: 0.5; /* 默认透明度 50% */
transition: opacity 0.3s;
}
.scroll-btn:hover {
opacity: 1; /* 悬浮时完全显示 */
}
#scroll-top {
margin-top: -40px; /* 向上移动40px */
}
#scroll-bottom {
margin-top: 40px; /* 向下移动40px */
}
`);
// 创建按钮
const createButton = (id, text) => {
const btn = document.createElement("div");
btn.id = id;
btn.className = "scroll-btn";
btn.innerHTML = text;
document.body.appendChild(btn);
// 点击后透明度降低到 25%
btn.addEventListener("click", () => {
btn.style.opacity = "0.25"; // 透明度降低
setTimeout(() => {
btn.style.opacity = "0.5"; // 2秒后恢复初始透明度
}, 2000);
});
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 easing = progress / duration; // 线性缓动
window.scrollTo(0, startY + distance * easing);
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();
})();
QingJ © 2025
镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址