Lite Add button for Smooth Scroll to the top / bottom

为页面添加按钮,平滑的滚动到顶部/底部

目前為 2015-08-01 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Lite Add button for Smooth Scroll to the top / bottom
  3. // @author burningall
  4. // @description 为页面添加按钮,平滑的滚动到顶部/底部
  5. // @version 2015.8.1
  6. // @include *
  7. // @supportURL http://www.burningall.com
  8. // @contributionURL troy450409405@gmail.com|alipay.com
  9. // @namespace https://greasyfork.org/zh-CN/users/3400-axetroy
  10. // ==/UserScript==
  11. //=======快捷键======
  12. //alt+1>>>>>>回到顶部
  13. //alt+2>>>>>>去到底部
  14. (function(document){
  15. //================公共函数区============
  16. function addEvent(obj, event, fn) {return obj.addEventListener ? obj.addEventListener(event, fn, false) : obj.attachEventListener("on" + event, fn);}
  17. function getSize(obj) {return document.documentElement[obj]!==0 ? document.documentElement[obj]: document.body[obj];}
  18. function scroll(obj,dir){//obj随意,dir>0往上滚,dir<0往下滚
  19. clearInterval(obj.timerScroll);
  20. obj.timerScroll=setInterval(function(){
  21. var position,speed;
  22. if(dir>0){//往上滚动
  23. speed = (getSize('scrollTop') / 10) + 1;
  24. position = getSize('scrollTop') - speed;
  25. if (position <= 0) {//如果滚到顶部
  26. document.body.scrollTop = document.documentElement.scrollTop = 0;
  27. clearInterval(obj.timerScroll);
  28. console.timeEnd('hello');
  29. }
  30. }else{//往下滚动
  31. speed = ((getSize('scrollHeight')-getSize('scrollTop')-getSize('clientHeight')) / 10) + 1;
  32. position = getSize('scrollTop') + speed;
  33. if (position + getSize('clientHeight') >= getSize('scrollHeight')) {//如果滚到底部
  34. document.body.scrollTop = document.documentElement.scrollTop = getSize('scrollHeight');
  35. clearInterval(obj.timerScroll);
  36. }
  37. }
  38. document.body.scrollTop = document.documentElement.scrollTop = position;
  39. },20);
  40. }
  41. //================快捷键区============
  42. addEvent(document,'keydown',function(e){
  43. e=e || window.top.event;
  44. if(e.altKey && e.keyCode == 49){//alt+1,向上滚动
  45. scroll(document,1);
  46. }else if(e.altKey && e.keyCode == 50) { //alt+2,向下滚动
  47. scroll(document,-1);
  48. }
  49. });
  50. })(document);