getElementRect.js.flow 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule getElementRect
  8. * @typechecks
  9. */
  10. const containsNode = require('./containsNode');
  11. /**
  12. * Gets an element's bounding rect in pixels relative to the viewport.
  13. *
  14. * @param {DOMElement} elem
  15. * @return {object}
  16. */
  17. function getElementRect(elem) {
  18. const docElem = elem.ownerDocument.documentElement;
  19. // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect().
  20. // IE9- will throw if the element is not in the document.
  21. if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) {
  22. return {
  23. left: 0,
  24. right: 0,
  25. top: 0,
  26. bottom: 0
  27. };
  28. }
  29. // Subtracts clientTop/Left because IE8- added a 2px border to the
  30. // <html> element (see http://fburl.com/1493213). IE 7 in
  31. // Quicksmode does not report clientLeft/clientTop so there
  32. // will be an unaccounted offset of 2px when in quirksmode
  33. const rect = elem.getBoundingClientRect();
  34. return {
  35. left: Math.round(rect.left) - docElem.clientLeft,
  36. right: Math.round(rect.right) - docElem.clientLeft,
  37. top: Math.round(rect.top) - docElem.clientTop,
  38. bottom: Math.round(rect.bottom) - docElem.clientTop
  39. };
  40. }
  41. module.exports = getElementRect;