scroll-to.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. Math.easeInOutQuad = function (t, b, c, d) {
  2. t /= d / 2;
  3. if (t < 1) {
  4. return (c / 2) * t * t + b;
  5. }
  6. t--;
  7. return (-c / 2) * (t * (t - 2) - 1) + b;
  8. };
  9. //requestAnimationFrame用于智能动画 http://goo.gl/sx5sts
  10. var requestAnimFrame = (function () {
  11. return (
  12. window.requestAnimationFrame ||
  13. window.webkitRequestAnimationFrame ||
  14. window.mozRequestAnimationFrame ||
  15. function (callback) {
  16. window.setTimeout(callback, 1000 / 60);
  17. }
  18. );
  19. })();
  20. /**
  21. * 因为要检测滚动元素太难了,把它们都移动就行了
  22. * @param {number} amount
  23. */
  24. function move(amount) {
  25. document.documentElement.scrollTop = amount;
  26. document.body.parentNode.scrollTop = amount;
  27. document.body.scrollTop = amount;
  28. }
  29. function position() {
  30. return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop;
  31. }
  32. /**
  33. * @param {number} to
  34. * @param {number} duration
  35. * @param {Function} callback
  36. */
  37. export function scrollTo(to, duration, callback) {
  38. const start = position();
  39. const change = to - start;
  40. const increment = 20;
  41. let currentTime = 0;
  42. duration = typeof duration === 'undefined' ? 500 : duration;
  43. var animateScroll = function () {
  44. // 增加次数
  45. currentTime += increment;
  46. // 用Math函数找到这个值
  47. var val = Math.easeInOutQuad(currentTime, start, change, duration);
  48. // 移动这个元素
  49. move(val);
  50. // 动画是否结束
  51. if (currentTime < duration) {
  52. requestAnimFrame(animateScroll);
  53. } else {
  54. if (callback && typeof callback === 'function') {
  55. //动画已经完成,进行回调
  56. callback();
  57. }
  58. }
  59. };
  60. animateScroll();
  61. }