scroll-controller.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. export abstract class ScrollController {
  2. abstract getScrollTop(): number
  3. abstract getScrollLeft(): number
  4. abstract setScrollTop(number): void
  5. abstract setScrollLeft(number): void
  6. abstract getClientWidth(): number
  7. abstract getClientHeight(): number
  8. abstract getScrollWidth(): number
  9. abstract getScrollHeight(): number
  10. getMaxScrollTop() {
  11. return this.getScrollHeight() - this.getClientHeight()
  12. }
  13. getMaxScrollLeft() {
  14. return this.getScrollWidth() - this.getClientWidth()
  15. }
  16. canScrollVertically() {
  17. return this.getMaxScrollTop() > 0
  18. }
  19. canScrollHorizontally() {
  20. return this.getMaxScrollLeft() > 0
  21. }
  22. canScrollUp() {
  23. return this.getScrollTop() > 0
  24. }
  25. canScrollDown() {
  26. return this.getScrollTop() < this.getMaxScrollTop()
  27. }
  28. canScrollLeft() {
  29. return this.getScrollLeft() > 0
  30. }
  31. canScrollRight() {
  32. return this.getScrollLeft() < this.getMaxScrollLeft()
  33. }
  34. }
  35. export class ElementScrollController extends ScrollController {
  36. el: HTMLElement
  37. constructor(el: HTMLElement) {
  38. super()
  39. this.el = el
  40. }
  41. getScrollTop() {
  42. return this.el.scrollTop
  43. }
  44. getScrollLeft() {
  45. return this.el.scrollLeft
  46. }
  47. setScrollTop(n: number) {
  48. this.el.scrollTop = n
  49. }
  50. setScrollLeft(n: number) {
  51. this.el.scrollLeft = n
  52. }
  53. getScrollWidth() {
  54. return this.el.scrollWidth
  55. }
  56. getScrollHeight() {
  57. return this.el.scrollHeight
  58. }
  59. getClientHeight() {
  60. return this.el.clientHeight
  61. }
  62. getClientWidth() {
  63. return this.el.clientWidth
  64. }
  65. }
  66. export class WindowScrollController extends ScrollController {
  67. getScrollTop() {
  68. return window.scrollY
  69. }
  70. getScrollLeft() {
  71. return window.scrollX
  72. }
  73. setScrollTop(n: number) {
  74. window.scroll(window.scrollX, n)
  75. }
  76. setScrollLeft(n: number) {
  77. window.scroll(n, window.scrollY)
  78. }
  79. getScrollWidth() {
  80. return document.documentElement.scrollWidth
  81. }
  82. getScrollHeight() {
  83. return document.documentElement.scrollHeight
  84. }
  85. getClientHeight() {
  86. return document.documentElement.clientHeight
  87. }
  88. getClientWidth() {
  89. return document.documentElement.clientWidth
  90. }
  91. }