要为每个页面添加一个“回到顶部”的按钮,可以使用油猴脚本来注入相应的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' });
});
})();
“`
解释
- 创建按钮:
- 使用
document.createElement
创建一个按钮元素。 - 设置按钮的
innerHTML
为一个向上的箭头符号(你也可以使用其他文本或图标)。 -
为按钮设置各种样式,使其看起来不错并且固定在页面的右下角。
-
添加到页面:
-
使用
document.body.appendChild
将按钮添加到页面的body
元素中。 -
显示和隐藏按钮:
- 使用
window.addEventListener('scroll')
监听滚动事件。 -
当页面滚动超过100像素时,显示按钮;否则,隐藏按钮。
-
滚动到顶部:
- 使用
button.addEventListener('click')
监听按钮的点击事件。 - 当按钮被点击时,使用
window.scrollTo
平滑滚动到页面顶部。
将这个脚本保存并启用后,每个页面都会有一个“回到顶部”的按钮。你可以根据需要调整按钮的样式和显示/隐藏逻辑。