scrollApi.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * @desc scroll滚动方法
  3. |*| * scrollApi.getScrollTop()
  4. |*| * scrollApi.setScrollTop(h)
  5. |*| * scrollApi.scrollTo(to,duration)
  6. */
  7. var requestAnimationFrame = function () {
  8. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
  9. window.setTimeout(callback, 1000 / 60);
  10. };
  11. }();
  12. var scrollApi = {
  13. getScrollTop: function getScrollTop() {
  14. return document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;
  15. },
  16. setScrollTop: function setScrollTop(h) {
  17. h && window.scrollTo(0, h);
  18. },
  19. scrollTo: function scrollTo(to) {
  20. var _this = this;
  21. var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  22. var minDecelerate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;
  23. var diff = to - this.getScrollTop();
  24. if (diff === 0) return;
  25. if (duration <= 0) {
  26. this.setScrollTop(to);
  27. return;
  28. }
  29. var step = diff / duration * 10;
  30. requestAnimationFrame(function () {
  31. if (Math.abs(step) > Math.abs(diff)) {
  32. _this.setScrollTop(_this.getScrollTop() + diff);
  33. return;
  34. }
  35. _this.setScrollTop(_this.getScrollTop() + step);
  36. if (diff > 0 && _this.getScrollTop() >= to || diff < 0 && _this.getScrollTop() <= to) {
  37. return;
  38. }
  39. _this.scrollTo(to, duration - 16 / minDecelerate);
  40. });
  41. }
  42. };
  43. module.exports = scrollApi;