油猴脚本给所有网页加一个“回到顶部”按钮

要为每个页面添加一个“回到顶部”的按钮,可以使用油猴脚本来注入相应的HTML和CSS,并添加JavaScript来实现这个功能。以下是一个完整的油猴脚本示例:

“`javascript
// ==UserScript==
// @name Add Back to Top Button
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Add a back to top button on every page
// @author You
// @match :///*
// @grant none
// ==/UserScript==

(function() {
‘use strict’;

// Create the button
const button = document.createElement('button');
button.innerHTML = '⬆️';
button.id = 'back-to-top-button';
button.style.position = 'fixed';
button.style.bottom = '20px';
button.style.right = '20px';
button.style.padding = '10px 15px';
button.style.fontSize = '20px';
button.style.backgroundColor = '#000';
button.style.color = '#fff';
button.style.border = 'none';
button.style.borderRadius = '5px';
button.style.cursor = 'pointer';
button.style.display = 'none'; // Hidden by default
button.style.zIndex = '1000';

// Append the button to the body
document.body.appendChild(button);

// Show the button when scrolling down 100px from the top of the document
window.addEventListener('scroll', () => {
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
        button.style.display = 'block';
    } else {
        button.style.display = 'none';
    }
});

// Scroll to the top when the button is clicked
button.addEventListener('click', () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
});

})();
“`

解释

  1. 创建按钮:
  2. 使用 document.createElement 创建一个按钮元素。
  3. 设置按钮的 innerHTML 为一个向上的箭头符号(你也可以使用其他文本或图标)。
  4. 为按钮设置各种样式,使其看起来不错并且固定在页面的右下角。

  5. 添加到页面:

  6. 使用 document.body.appendChild 将按钮添加到页面的 body 元素中。

  7. 显示和隐藏按钮:

  8. 使用 window.addEventListener('scroll') 监听滚动事件。
  9. 当页面滚动超过100像素时,显示按钮;否则,隐藏按钮。

  10. 滚动到顶部:

  11. 使用 button.addEventListener('click') 监听按钮的点击事件。
  12. 当按钮被点击时,使用 window.scrollTo 平滑滚动到页面顶部。

将这个脚本保存并启用后,每个页面都会有一个“回到顶部”的按钮。你可以根据需要调整按钮的样式和显示/隐藏逻辑。

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部