滚动到顶部按钮

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

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

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

(function() {
    'use strict';

    // 创建按钮元素
    var scrollButton = document.createElement('div');
    scrollButton.classList.add('goto_top');
    scrollButton.innerHTML = '<div><i class="goto-top" style="display: block;"></i></div>';

    // 添加按钮到页面
    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); // 将页面滚动到顶部
    });

    // 添加按钮样式
    var style = document.createElement('style');
    style.innerHTML = `
        .goto_top {
            display: none;
            content: '';
            width: .4rem;
            height: .4rem;
            position: fixed;
            bottom: 2rem;
            right: .3rem;
            background: url("https://obj.pipi.cn/festatic/moviepro/img/movie-home/gototop-a6ba6fb8.png");
            background-size: contain;
            z-index: 9999;
            cursor: pointer;
        }

        .goto_top img {
            display: block;
            width: 100%;
            height: 100%;
        }

        .goto_top:hover {
            background-color: #ccc;
        }
    `;
    document.head.appendChild(style);
})();

QingJ © 2025

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