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.2
  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. timeoutID = null;
  33. }, 2000);
  34. }
  35.  
  36. function addCSSStyle() {
  37. var cssStyle = document.createElement('style');
  38. cssStyle.type = 'text/css';
  39. cssStyle.textContent = [
  40. '.' + sttClassName + ' {',
  41. ' width: 10vw;',
  42. ' height: 10vw;',
  43. ' line-height: 10vw;',
  44. ' text-align: center;',
  45. ' background: whiteSmoke;',
  46. ' font-weight: bold;',
  47. ' font-size: 8vw;',
  48. ' color: #444;',
  49. ' text-decoration: none;',
  50. ' position: fixed;',
  51. ' bottom: 0;',
  52. ' left: 0;',
  53. ' display: block;',
  54. ' border: 1px solid grey;',
  55. ' border-top-right-radius: 5vw;',
  56. ' box-shadow: 0 0 3px grey;',
  57. ' transition: opacity 250ms ease-out;',
  58. ' opacity: .1;',
  59. ' z-index: 1000;',
  60. ' cursor: pointer;',
  61. '}'
  62. ].join('\n');
  63. if(document.head) {
  64. document.head.appendChild(cssStyle);
  65. }
  66. }
  67.  
  68. (() => {
  69. if ('ontouchstart' in window) {
  70. window.ontouchmove = scroll_or_touchmove_handler;
  71. } else {
  72. window.onscroll = scroll_or_touchmove_handler;
  73. window.onwheel = function() {
  74. if(typeof timeoutID != 'number') {
  75. return;
  76. }
  77. clearTimeout(timeoutID);
  78. timeoutID = null;
  79. };
  80.  
  81. }
  82. addCSSStyle();
  83. var div = document.createElement('div');
  84. div.className = sttClassName;
  85. div.textContent = '⇧';
  86. div.onclick = () => window.scrollTo(0, 0);
  87. document.body.appendChild(div);
  88.  
  89.  
  90. })();
  91.  
  92. })();