返回顶部按钮

给页面右下角添加返回顶部按钮

  1. // ==UserScript==
  2. // @name 返回顶部按钮
  3. // @namespace https://github.com/nameldk/user-script
  4. // @version 0.6
  5. // @description 给页面右下角添加返回顶部按钮
  6. // @author nameldk
  7. // @match *://*/*
  8. // @run-at document-body
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function () {
  13. 'use strict';
  14. var a = document.createElement('a');
  15. if (!a) return;
  16. a.href = "javascript:;";
  17. a.text = "TOP";
  18. a.style.position = "fixed";
  19. a.style.right = "5%";
  20. a.style.bottom = "25%";
  21. a.style.fontSize = "20px";
  22. a.style.textDecoration = "none";
  23. a.style.zIndex = 9999;
  24. a.style.display = "none";
  25. document.querySelector("body").appendChild(a);
  26.  
  27. var enterRightBottom = 0;
  28. var leaveTop = 0;
  29.  
  30. function showHide() {
  31. if (leaveTop && enterRightBottom) {
  32. a.style.display = "block";
  33. } else {
  34. a.style.display = "none";
  35. }
  36. }
  37.  
  38. function animate({
  39. timing,
  40. draw,
  41. duration
  42. }) {
  43. let start = performance.now();
  44.  
  45. requestAnimationFrame(function animate(time) {
  46. // timeFraction goes from 0 to 1
  47. let timeFraction = (time - start) / duration;
  48. if (timeFraction > 1) timeFraction = 1;
  49.  
  50. // calculate the current animation state
  51. let progress = timing(timeFraction)
  52.  
  53. draw(progress); // draw it
  54.  
  55. if (timeFraction < 1) {
  56. requestAnimationFrame(animate);
  57. }
  58.  
  59. });
  60. }
  61.  
  62. window.addEventListener("mousemove", function (e) {
  63. enterRightBottom = e.clientX > window.innerWidth / 4 * 3 && e.clientY > window.innerHeight / 3 * 2;
  64. showHide();
  65. });
  66.  
  67. window.addEventListener("scroll", function () {
  68. leaveTop = (+(document.body.scrollTop || document.documentElement.scrollTop) > 100);
  69. showHide();
  70. });
  71.  
  72. a.addEventListener("click", function () {
  73. var height = window.scrollY;
  74. if (height === 0) return;
  75. animate({
  76. timing: function (timeFraction) {
  77. return 0.5 - Math.cos(timeFraction * Math.PI) / 2;
  78. },
  79. draw: function (progress) {
  80. window.scroll(0, height * (1 - progress));
  81. },
  82. duration: 200
  83. });
  84. });
  85.  
  86. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址