scroll.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. type ScrollElement = HTMLElement | Window;
  2. // get nearest scroll element
  3. // http://w3help.org/zh-cn/causes/SD9013
  4. // http://stackoverflow.com/questions/17016740/onscroll-function-is-not-working-for-chrome
  5. export function getScrollEventTarget(element: HTMLElement, rootParent: ScrollElement = window) {
  6. let node = element;
  7. while (
  8. node &&
  9. node.tagName !== 'HTML' &&
  10. node.tagName !== 'BODY' &&
  11. node.nodeType === 1 &&
  12. node !== rootParent
  13. ) {
  14. const { overflowY } = window.getComputedStyle(node);
  15. if (overflowY === 'scroll' || overflowY === 'auto') {
  16. return node;
  17. }
  18. node = <HTMLElement>node.parentNode;
  19. }
  20. return rootParent;
  21. }
  22. export function getScrollTop(element: ScrollElement): number {
  23. return 'scrollTop' in element ? element.scrollTop : element.pageYOffset;
  24. }
  25. export function setScrollTop(element: ScrollElement, value: number) {
  26. 'scrollTop' in element ? (element.scrollTop = value) : element.scrollTo(element.scrollX, value);
  27. }
  28. export function getRootScrollTop(): number {
  29. return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  30. }
  31. // get distance from element top to page top
  32. export function getElementTop(element: ScrollElement) {
  33. return (
  34. (element === window ? 0 : (<HTMLElement>element).getBoundingClientRect().top) +
  35. getScrollTop(window)
  36. );
  37. }
  38. export function getVisibleHeight(element: ScrollElement) {
  39. return element === window
  40. ? element.innerHeight
  41. : (<HTMLElement>element).getBoundingClientRect().height;
  42. }