点击返回顶部

点击向上的箭头按钮返回到页面顶部

目前为 2017-06-26 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Click To Top
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.41
  5. // @description click the arrow-up pic to jump to the top of page.
  6. // @author kilin
  7. // @include *
  8. // @match *
  9. // @grant none
  10. // @name:zh-CN 点击返回顶部
  11. // @description:zh-CN 点击向上的箭头按钮返回到页面顶部
  12. // ==/UserScript==
  13.  
  14. (function(){window.onload = function(){
  15. console.log('DOM already loaded.');
  16. if(window.top == window.self){
  17. var aNode = document.createElement('a');
  18. aNode.href = 'javascript:;';
  19. aNode.id = 'click-to-top';
  20. aNode.title = 'Click it to go to the top';
  21. var availHeight = window.screen.availHeight; // 获取可用高度
  22. var css = '#click-to-top{ display:none; position: fixed; right: 5%; bottom: 20%; opacity: 0.2; z-index: 9999; } #click-to-top:hover{ position: fixed; right: 5%; bottom: 20%; opacity: 1; z-index: 9999; }';
  23. //滚出一屏以后才显示返回顶部按钮
  24. window.onscroll = function(){
  25. var curPos = document.documentElement.scrollTop; //preparation for hack (document.documentElement.scrollTop == 0) ? document.body.scrollTop : document.documentElement.scrollTop;
  26. if(curPos > availHeight){
  27. aNode.style.display = 'block';
  28. }else {
  29. aNode.style.display = 'none';
  30. }
  31. };
  32. //图片相关
  33. var img = document.createElement('img');
  34. img.src = 'https://ooo.0o0.ooo/2017/05/23/59245c636b321.png';
  35. img.style = 'width: 30px; height: 30px;';
  36. //样式相关
  37. var style = document.createElement('style');
  38. if (style.styleSheet) {
  39. style.styleSheet.cssText = css;
  40. } else {
  41. style.appendChild(document.createTextNode(css));
  42. }
  43. document.getElementsByTagName('head')[0].appendChild(style);
  44. aNode.append(img);
  45. aNode.addEventListener('click', function(){
  46. document.body.scrollIntoView();
  47. /*var timer = setInterval(function(){
  48. document.documentElement.scrollTop -= 500;
  49. if(document.documentElement.scrollTop < 100){
  50. clearInterval(timer);
  51. }
  52. }, 50);
  53. }, true);*/
  54. });
  55. var eBody = document.querySelector('body');
  56. eBody.append(aNode);
  57. }
  58. };})();