scroll.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. function isWindow(val) {
  2. return val === window;
  3. } // get nearest scroll element
  4. // https://github.com/vant-ui/vant/issues/3823
  5. var overflowScrollReg = /scroll|auto|overlay/i;
  6. export function getScroller(el, root) {
  7. if (root === void 0) {
  8. root = window;
  9. }
  10. var node = el;
  11. while (node && node.tagName !== 'HTML' && node.tagName !== 'BODY' && node.nodeType === 1 && node !== root) {
  12. var _window$getComputedSt = window.getComputedStyle(node),
  13. overflowY = _window$getComputedSt.overflowY;
  14. if (overflowScrollReg.test(overflowY)) {
  15. return node;
  16. }
  17. node = node.parentNode;
  18. }
  19. return root;
  20. }
  21. export function getScrollTop(el) {
  22. var top = 'scrollTop' in el ? el.scrollTop : el.pageYOffset; // iOS scroll bounce cause minus scrollTop
  23. return Math.max(top, 0);
  24. }
  25. export function setScrollTop(el, value) {
  26. if ('scrollTop' in el) {
  27. el.scrollTop = value;
  28. } else {
  29. el.scrollTo(el.scrollX, value);
  30. }
  31. }
  32. export function getRootScrollTop() {
  33. return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  34. }
  35. export function setRootScrollTop(value) {
  36. setScrollTop(window, value);
  37. setScrollTop(document.body, value);
  38. } // get distance from element top to page top or scroller top
  39. export function getElementTop(el, scroller) {
  40. if (isWindow(el)) {
  41. return 0;
  42. }
  43. var scrollTop = scroller ? getScrollTop(scroller) : getRootScrollTop();
  44. return el.getBoundingClientRect().top + scrollTop;
  45. }
  46. export function getVisibleHeight(el) {
  47. if (isWindow(el)) {
  48. return el.innerHeight;
  49. }
  50. return el.getBoundingClientRect().height;
  51. }
  52. export function getVisibleTop(el) {
  53. if (isWindow(el)) {
  54. return 0;
  55. }
  56. return el.getBoundingClientRect().top;
  57. }