Scroll to Top and Bottom

Add buttons to scroll to top and bottom of the page on all websites

  1. // ==UserScript==
  2. // @name Scroll to Top and Bottom
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  5. // @license MIT
  6. // @description Add buttons to scroll to top and bottom of the page on all websites
  7. // @author shanhai
  8. // @match *://*/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // 创建按钮的样式
  16. const buttonStyle = `
  17. position: fixed;
  18. right: 20px;
  19. padding: 10px 15px;
  20. //width: 30px;
  21. //height: 18px;
  22. font-size: 14px;
  23. background-color: #f39c12;
  24. color: white;
  25. border: none;
  26. border-radius: 5px;
  27. cursor: pointer;
  28. z-index: 9999;
  29. box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  30. display: none; /* 默认隐藏按钮 */
  31. `;
  32.  
  33. // 创建 "Top" 按钮
  34. const topButton = document.createElement('button');
  35. topButton.innerHTML = '⤊';//⬆⭡⇈ Top
  36. topButton.style = buttonStyle + 'bottom: 80px;';
  37. topButton.onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' });
  38.  
  39. // 创建 "Bottom" 按钮
  40. const bottomButton = document.createElement('button');
  41. bottomButton.innerHTML = '⤋';//⬇ Bottom
  42. bottomButton.style = buttonStyle + 'bottom: 20px;';
  43. bottomButton.onclick = () => {
  44. const footElement = document.getElementById("rhf");
  45. if(footElement){
  46. window.scrollTo(0, footElement.offsetTop);
  47. }else{
  48. window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
  49. }
  50. }
  51.  
  52. // 把按钮加到页面上
  53. document.body.appendChild(topButton);
  54. document.body.appendChild(bottomButton);
  55.  
  56. // 监听滚动事件
  57. window.addEventListener('scroll', () => {
  58. const scrollY = window.scrollY;
  59. const scrollHeight = document.body.scrollHeight;
  60. const clientHeight = document.documentElement.clientHeight;
  61.  
  62. //console.log('ScrollY:', scrollY);
  63. //console.log('ScrollHeight:', scrollHeight);
  64. //console.log('ClientHeight:', clientHeight);
  65.  
  66.  
  67. // 如果滚动到顶部,隐藏 "Top" 按钮,否则显示
  68. if (scrollY === 0) {
  69. topButton.style.display = 'none';
  70. } else {
  71. topButton.style.display = 'block';
  72. }
  73.  
  74. // 如果滚动到底部,隐藏 "Bottom" 按钮,否则显示
  75. if (scrollY + clientHeight +10 >= scrollHeight) {
  76. bottomButton.style.display = 'none';
  77. } else {
  78. bottomButton.style.display = 'block';
  79. }
  80. });
  81. })();