滚动到顶部按钮

在网页添加一个“回到顶部”的按钮,可以快速回到页面顶部。

目前為 2023-03-08 提交的版本,檢視 最新版本

// ==UserScript==
// @name         滚动到顶部按钮
// @namespace    http://tampermonkey.net/
// @version      1.3
// @description  在网页添加一个“回到顶部”的按钮,可以快速回到页面顶部。
// @author       Techwb.cn
// @match        https://*/*
// @match        http://*/*
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // 创建按钮元素
    var scrollButton = document.createElement('button');
    scrollButton.textContent = '回到顶部';
    scrollButton.id = 'scroll-top-button';

    // 添加按钮样式
    scrollButton.style.background = 'red'; // 将背景颜色改为红色
    scrollButton.style.border = 'none'; // 去掉边框
    scrollButton.style.color = 'white'; // 文字颜色为白色
    scrollButton.style.padding = '10px 10px'; // 设定按钮的内边距
    scrollButton.style.textAlign = 'center'; // 文字居中
    scrollButton.style.textDecoration = 'none'; // 去掉下划线
    scrollButton.style.display = 'none'; // 默认不显示
    scrollButton.style.borderRadius = '10px'; // 设定圆角
    scrollButton.style.boxShadow = '2px 2px 3px rgba(0, 0, 0, 0.3)'; // 添加阴影效果
    scrollButton.style.cursor = 'pointer'; // 设定鼠标样式为手型
    scrollButton.style.position = 'fixed'; // 设定固定定位
    scrollButton.style.bottom = '8%'; // 设定距离底部的距离
    scrollButton.style.right = '20px'; // 设定距离右侧的距离
    scrollButton.style.zIndex = '9999'; // 设定 z-index

    // 添加鼠标悬停效果
    scrollButton.addEventListener('mouseenter', function() {
        scrollButton.style.backgroundColor = '#ff6347'; // 鼠标悬停时的背景颜色
    });

    scrollButton.addEventListener('mouseleave', function() {
        scrollButton.style.backgroundColor = 'red'; // 鼠标离开时的背景颜色
    });

    // 添加按钮到页面
    document.body.appendChild(scrollButton);

    // 当用户滚动页面时,如果已经滚动了一定距离,就显示按钮
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 100) { // 滚动距离超过 100px 时
            scrollButton.style.display = 'block'; // 显示按钮
        } else {
            scrollButton.style.display = 'none'; // 否则隐藏按钮
        }
    });

    // 点击按钮时,回到页面顶部
    scrollButton.addEventListener('click', function() {
        window.scrollTo(0, 0); // 将页面滚动到顶部
    });
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址