utils.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { raf, cancelRaf } from "@vant/use";
  2. import { getScrollTop, setScrollTop } from "../utils/index.mjs";
  3. function scrollLeftTo(scroller, to, duration) {
  4. let rafId;
  5. let count = 0;
  6. const from = scroller.scrollLeft;
  7. const frames = duration === 0 ? 1 : Math.round(duration * 1e3 / 16);
  8. let scrollLeft = from;
  9. function cancel() {
  10. cancelRaf(rafId);
  11. }
  12. function animate() {
  13. scrollLeft += (to - from) / frames;
  14. scroller.scrollLeft = scrollLeft;
  15. if (++count < frames) {
  16. rafId = raf(animate);
  17. }
  18. }
  19. animate();
  20. return cancel;
  21. }
  22. function scrollTopTo(scroller, to, duration, callback) {
  23. let rafId;
  24. let current = getScrollTop(scroller);
  25. const isDown = current < to;
  26. const frames = duration === 0 ? 1 : Math.round(duration * 1e3 / 16);
  27. const step = (to - current) / frames;
  28. function cancel() {
  29. cancelRaf(rafId);
  30. }
  31. function animate() {
  32. current += step;
  33. if (isDown && current > to || !isDown && current < to) {
  34. current = to;
  35. }
  36. setScrollTop(scroller, current);
  37. if (isDown && current < to || !isDown && current > to) {
  38. rafId = raf(animate);
  39. } else if (callback) {
  40. rafId = raf(callback);
  41. }
  42. }
  43. animate();
  44. return cancel;
  45. }
  46. export {
  47. scrollLeftTo,
  48. scrollTopTo
  49. };