utils.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { raf, cancelRaf } from '../utils/dom/raf';
  2. import { getScrollTop, setScrollTop } from '../utils/dom/scroll';
  3. var scrollLeftRafId;
  4. export function scrollLeftTo(scroller, to, duration) {
  5. cancelRaf(scrollLeftRafId);
  6. var count = 0;
  7. var from = scroller.scrollLeft;
  8. var frames = duration === 0 ? 1 : Math.round(duration * 1000 / 16);
  9. function animate() {
  10. scroller.scrollLeft += (to - from) / frames;
  11. if (++count < frames) {
  12. scrollLeftRafId = raf(animate);
  13. }
  14. }
  15. animate();
  16. }
  17. export function scrollTopTo(scroller, to, duration, callback) {
  18. var current = getScrollTop(scroller);
  19. var isDown = current < to;
  20. var frames = duration === 0 ? 1 : Math.round(duration * 1000 / 16);
  21. var step = (to - current) / frames;
  22. function animate() {
  23. current += step;
  24. if (isDown && current > to || !isDown && current < to) {
  25. current = to;
  26. }
  27. setScrollTop(scroller, current);
  28. if (isDown && current < to || !isDown && current > to) {
  29. raf(animate);
  30. } else if (callback) {
  31. raf(callback);
  32. }
  33. }
  34. animate();
  35. }