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) ? // In practice, they will either both have the same value,
  37. // or one will be zero and the other will be the scroll position
  38. // of the viewport. So we can use `X || Y` instead of `Math.max(X, Y)`
  39. doc.body.scrollTop || doc.documentElement.scrollTop : element.scrollTop;
  40. },
  41. /**
  42. * @param {DOMElement} element
  43. * @param {number} newTop
  44. */
  45. setTop: function setTop(element, newTop) {
  46. var doc = element.ownerDocument;
  47. if (_isViewportScrollElement(element, doc)) {
  48. doc.body.scrollTop = doc.documentElement.scrollTop = newTop;
  49. } else {
  50. element.scrollTop = newTop;
  51. }
  52. },
  53. /**
  54. * @param {DOMElement} element
  55. * @return {number}
  56. */
  57. getLeft: function getLeft(element) {
  58. var doc = element.ownerDocument;
  59. return _isViewportScrollElement(element, doc) ? doc.body.scrollLeft || doc.documentElement.scrollLeft : element.scrollLeft;
  60. },
  61. /**
  62. * @param {DOMElement} element
  63. * @param {number} newLeft
  64. */
  65. setLeft: function setLeft(element, newLeft) {
  66. var doc = element.ownerDocument;
  67. if (_isViewportScrollElement(element, doc)) {
  68. doc.body.scrollLeft = doc.documentElement.scrollLeft = newLeft;
  69. } else {
  70. element.scrollLeft = newLeft;
  71. }
  72. }
  73. };
  74. module.exports = Scroll;