scroll_to_top

scroll to top for PC and mobile

当前为 2022-02-03 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name scroll_to_top
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  5. // @description scroll to top for PC and mobile
  6. // @author amormaid
  7. // @run-at document-end
  8. // @match http(s)?://*/*
  9. // @include http://*
  10. // @include https://*
  11. // @icon https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
  12. // @grant none
  13. // @license MIT
  14. // ==/UserScript==
  15.  
  16. (function() {
  17. 'use strict';
  18.  
  19. const sttClassName = 'scroll-to-top';
  20. let timeoutID;
  21.  
  22. function scroll_or_touchmove_handler() {
  23. clearTimeout(timeoutID);
  24. timeoutID = setTimeout(() => {
  25. const btn = (document.getElementsByClassName(sttClassName) || [])[0];
  26. if (btn) {
  27. btn.style.cssText = 'opacity: 1;';
  28. setTimeout(() => {
  29. btn.style.cssText = 'opacity: .1;';
  30. }, 5000)
  31. }
  32.  
  33. timeoutID = null;
  34. }, 50);
  35. }
  36.  
  37. function addCSSStyle() {
  38. var cssStyle = document.createElement('style');
  39. cssStyle.type = 'text/css';
  40. cssStyle.textContent = [
  41. '.' + sttClassName + ' {',
  42. ' width: 8vw;',
  43. ' height: 8vw;',
  44. ' line-height: 8vw;',
  45. ' text-align: center;',
  46. ' background: whiteSmoke;',
  47. ' font-weight: bold;',
  48. ' font-size: 6vw;',
  49. ' color: #444;',
  50. ' text-decoration: none;',
  51. ' position: fixed;',
  52. ' bottom: 0;',
  53. ' left: 0;',
  54. ' display: block;',
  55. ' border: 1px solid grey;',
  56. ' border-top-right-radius: 4vw;',
  57. ' box-shadow: 0 0 3px grey;',
  58. ' transition: opacity 250ms ease-out;',
  59. ' opacity: .1;',
  60. ' z-index: 1000;',
  61. ' cursor: pointer;',
  62. '}'
  63. ].join('\n');
  64. if(document.head) {
  65. document.head.appendChild(cssStyle);
  66. }
  67. }
  68.  
  69. (() => {
  70. if ('ontouchstart' in window) {
  71. window.ontouchmove = scroll_or_touchmove_handler;
  72. } else {
  73. window.onscroll = scroll_or_touchmove_handler;
  74. window.onwheel = function() {
  75. if(typeof timeoutID != 'number') {
  76. return;
  77. }
  78. clearTimeout(timeoutID);
  79. timeoutID = null;
  80. };
  81.  
  82. }
  83. addCSSStyle();
  84. var div = document.createElement('div');
  85. div.className = sttClassName;
  86. div.textContent = '⇧';
  87. div.onclick = () => window.scrollTo(0, 0);
  88. document.body.appendChild(div);
  89.  
  90.  
  91. })();
  92.  
  93. })();