scroll-to.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import el from "element-ui/src/locale/lang/el";
  2. Math.easeInOutQuad = function(t, b, c, d) {
  3. t /= d / 2
  4. if (t < 1) {
  5. return c / 2 * t * t + b
  6. }
  7. t--
  8. return -c / 2 * (t * (t - 2) - 1) + b
  9. }
  10. // requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
  11. var requestAnimFrame = (function() {
  12. if (window!=null) {
  13. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60) }
  14. }else {
  15. return null;
  16. }
  17. })
  18. /**
  19. * Because it's so fucking difficult to detect the scrolling element, just move them all
  20. * @param {number} amount
  21. */
  22. function move(amount) {
  23. document.documentElement.scrollTop = amount
  24. document.body.parentNode.scrollTop = amount
  25. document.body.scrollTop = amount
  26. }
  27. function position() {
  28. return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
  29. }
  30. /**
  31. * @param {number} to
  32. * @param {number} duration
  33. * @param {Function} callback
  34. */
  35. export function scrollTo(to, duration, callback) {
  36. const start = position()
  37. const change = to - start
  38. const increment = 20
  39. let currentTime = 0
  40. duration = (typeof (duration) === 'undefined') ? 500 : duration
  41. var animateScroll = function() {
  42. // increment the time
  43. currentTime += increment
  44. // find the value with the quadratic in-out easing function
  45. var val = Math.easeInOutQuad(currentTime, start, change, duration)
  46. // move the document.body
  47. move(val)
  48. // do the animation unless its over
  49. if (currentTime < duration) {
  50. requestAnimFrame(animateScroll)
  51. } else {
  52. if (callback && typeof (callback) === 'function') {
  53. // the animation is done so lets callback
  54. callback()
  55. }
  56. }
  57. }
  58. animateScroll()
  59. }