smooth-scroll.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame
  2. const Quad_easeIn = (t, b, c, d) => c * ((t = t / d - 1) * t * t + 1) + b
  3. const scrollTo = (end, time = 800) => {
  4. let scrollTop = window.pageYOffset || document.documentElement.scrollTop
  5. let b = scrollTop
  6. let c = end - b
  7. let d = time
  8. let start = null
  9. return new Promise((resolve, reject) => {
  10. function step(timeStamp) {
  11. if (start === null) start = timeStamp
  12. let progress = timeStamp - start
  13. if (progress < time) {
  14. let st = Quad_easeIn(progress, b, c, d)
  15. document.body.scrollTop = st
  16. document.documentElement.scrollTop = st
  17. window.requestAnimationFrame(step)
  18. }
  19. else {
  20. document.body.scrollTop = end
  21. document.documentElement.scrollTop = end
  22. resolve(end)
  23. }
  24. }
  25. window.requestAnimationFrame(step)
  26. })
  27. }
  28. const scrollToTop = (time) => {
  29. time = typeof time === 'number' ? time : 800
  30. return scrollTo(0, time)
  31. }
  32. const scrollToElem = (elem, time, offset) => {
  33. let top = elem.getBoundingClientRect().top + ( window.pageYOffset || document.documentElement.scrollTop ) - ( document.documentElement.clientTop || 0 )
  34. return scrollTo(top - (offset || 0), time)
  35. }
  36. export default {
  37. methods: {
  38. scrollToTop,
  39. scrollToElem,
  40. scrollTo
  41. }
  42. }