Back to Top Button

右下角固定返回顶部按钮

  1. // ==UserScript==
  2. // @name Back to Top Button
  3. // @namespace github.com/aioi50
  4. // @version 1.0
  5. // @description 右下角固定返回顶部按钮
  6. // @author Cline
  7. // @match *://*/*
  8. // @grant none
  9. // ==/UserScript==
  10.  
  11. (function() {
  12. 'use strict';
  13.  
  14. // 创建按钮元素
  15. const btn = document.createElement('button');
  16. btn.innerHTML = '↑';
  17. btn.id = 'backToTopBtn';
  18.  
  19. // 设置按钮样式
  20. btn.style.cssText = `
  21. position: fixed;
  22. bottom: 40px;
  23. right: 40px;
  24. width: 50px;
  25. height: 50px;
  26. border-radius: 50%;
  27. background: #007bff;
  28. color: white;
  29. font-size: 24px;
  30. border: none;
  31. cursor: pointer;
  32. opacity: 0.8;
  33. transition: opacity 0.3s;
  34. display: none;
  35. z-index: 9999;
  36. `;
  37.  
  38. // 添加按钮到页面
  39. document.body.appendChild(btn);
  40.  
  41. // 滚动事件监听
  42. window.addEventListener('scroll', function() {
  43. if (window.scrollY > 300) {
  44. btn.style.display = 'block';
  45. btn.style.opacity = '0.8';
  46. } else {
  47. btn.style.opacity = '0';
  48. setTimeout(() => { btn.style.display = 'none' }, 300);
  49. }
  50. });
  51.  
  52. // 点击事件处理
  53. btn.addEventListener('click', function() {
  54. window.scrollTo({
  55. top: 0,
  56. behavior: 'smooth'
  57. });
  58. });
  59.  
  60. })();