点击返回顶部

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

当前为 2017-06-08 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Click To Top
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.3
  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. window.onload = function(){
  15. console.log('DOM already loaded.');
  16. if(window.top == window.self){ var aNode = document.createElement('a');
  17. aNode.href = 'javascript:;';
  18. aNode.id = 'click-to-top';
  19. aNode.title = 'Click it to go to the top';
  20. var availHeight = window.screen.availHeight; // 获取可用高度
  21. 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; }';
  22. //滚出一屏以后才显示返回顶部按钮
  23. window.onscroll = function(){
  24. var curPos = document.documentElement.scrollTop;
  25. if(curPos > availHeight){
  26. aNode.style.display = 'block';
  27. }else {
  28. aNode.style.display = 'none';
  29. }
  30. };
  31. //图片相关
  32. var img = document.createElement('img');
  33. img.src = 'https://ooo.0o0.ooo/2017/05/23/59245c636b321.png';
  34. img.style = 'width: 30px; height: 30px;';
  35. //样式相关
  36. var style = document.createElement('style');
  37. if (style.styleSheet) {
  38. style.styleSheet.cssText = css;
  39. } else {
  40. style.appendChild(document.createTextNode(css));
  41. }
  42. document.getElementsByTagName('head')[0].appendChild(style);
  43. aNode.append(img);
  44. aNode.addEventListener('click', function(){
  45. //document.body.scrollIntoView();
  46. var timer = setInterval(function(){
  47. document.documentElement.scrollTop -= 500;
  48. if(document.documentElement.scrollTop < 100){
  49. clearInterval(timer);
  50. }
  51. }, 50);
  52. }, true);
  53. var eBody = document.querySelector('body');
  54. eBody.append(aNode);};
  55.  
  56. };