Geekhub scrollTop

Geekhub 返回顶部

  1. // ==UserScript==
  2. // @name Geekhub scrollTop
  3. // @namespace http://wenyi.me
  4. // @version 0.4
  5. // @description Geekhub 返回顶部
  6. // @author SeaMonster
  7. // @match https://*.geekhub.com/*
  8. // @grant none
  9. // ==/UserScript==
  10.  
  11. try {
  12. var body = document.body;
  13. var div = document.createElement("div");
  14. div.id = "myBtn";
  15. div.setAttribute("style",
  16. "display: none;position: fixed;bottom: 160px;right: 50px;z-index: 99; outline: none;background-color: #fff;color: #333;cursor: pointer;border-radius: 10px;box-shadow: 0 2px 4px 0 rgba(0,0,0,.05);"
  17. );
  18. div.innerHTML = '<button onclick="topFunction()" style="padding: 15px;" id="myBtn" title="回顶部">Top</button>';
  19. body.appendChild(div);
  20. } catch (e) {
  21. console.log("scroll Error");
  22. }
  23. // 当网页向下滑动 300px 出现"返回顶部" 按钮
  24. window.onscroll = function () {
  25. scrollFunction()
  26. };
  27.  
  28. function scrollFunction() {
  29. console.log(121);
  30. if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
  31. document.getElementById("myBtn").style.display = "block";
  32. } else {
  33. document.getElementById("myBtn").style.display = "none";
  34. }
  35. }
  36. // 点击按钮,返回顶部
  37. window.topFunction = function topFunction() {
  38. (function smoothscroll() {
  39. var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
  40. if (currentScroll > 0) {
  41. window.requestAnimationFrame(smoothscroll);
  42. window.scrollTo(0, currentScroll - (currentScroll / 5));
  43. }
  44. })();
  45. }