Scroll.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. /**
  3. * Copyright (c) 2013-present, Facebook, Inc.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. */
  9. /**
  10. * @param {DOMElement} element
  11. * @param {DOMDocument} doc
  12. * @return {boolean}
  13. */
  14. function _isViewportScrollElement(element, doc) {
  15. return !!doc && (element === doc.documentElement || element === doc.body);
  16. }
  17. /**
  18. * Scroll Module. This class contains 4 simple static functions
  19. * to be used to access Element.scrollTop/scrollLeft properties.
  20. * To solve the inconsistencies between browsers when either
  21. * document.body or document.documentElement is supplied,
  22. * below logic will be used to alleviate the issue:
  23. *
  24. * 1. If 'element' is either 'document.body' or 'document.documentElement,
  25. * get whichever element's 'scroll{Top,Left}' is larger.
  26. * 2. If 'element' is either 'document.body' or 'document.documentElement',
  27. * set the 'scroll{Top,Left}' on both elements.
  28. */
  29. var Scroll = {
  30. /**
  31. * @param {DOMElement} element
  32. * @return {number}
  33. */
  34. getTop: function getTop(element) {
  35. var doc = element.ownerDocument;
  36. return _isViewportScrollElement(element, doc) ?
  37. // In practice, they will either both have the same value,
  38. // or one will be zero and the other will be the scroll position
  39. // of the viewport. So we can use `X || Y` instead of `Math.max(X, Y)`
  40. doc.body.scrollTop || doc.documentElement.scrollTop : element.scrollTop;
  41. },
  42. /**
  43. * @param {DOMElement} element
  44. * @param {number} newTop
  45. */
  46. setTop: function setTop(element, newTop) {
  47. var doc = element.ownerDocument;
  48. if (_isViewportScrollElement(element, doc)) {
  49. doc.body.scrollTop = doc.documentElement.scrollTop = newTop;
  50. } else {
  51. element.scrollTop = newTop;
  52. }
  53. },
  54. /**
  55. * @param {DOMElement} element
  56. * @return {number}
  57. */
  58. getLeft: function getLeft(element) {
  59. var doc = element.ownerDocument;
  60. return _isViewportScrollElement(element, doc) ? doc.body.scrollLeft || doc.documentElement.scrollLeft : element.scrollLeft;
  61. },
  62. /**
  63. * @param {DOMElement} element
  64. * @param {number} newLeft
  65. */
  66. setLeft: function setLeft(element, newLeft) {
  67. var doc = element.ownerDocument;
  68. if (_isViewportScrollElement(element, doc)) {
  69. doc.body.scrollLeft = doc.documentElement.scrollLeft = newLeft;
  70. } else {
  71. element.scrollLeft = newLeft;
  72. }
  73. }
  74. };
  75. module.exports = Scroll;