getElementRect.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. * @typechecks
  9. */
  10. var 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. var docElem = elem.ownerDocument.documentElement; // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect().
  19. // IE9- will throw if the element is not in the document.
  20. if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) {
  21. return {
  22. left: 0,
  23. right: 0,
  24. top: 0,
  25. bottom: 0
  26. };
  27. } // Subtracts clientTop/Left because IE8- added a 2px border to the
  28. // <html> element (see http://fburl.com/1493213). IE 7 in
  29. // Quicksmode does not report clientLeft/clientTop so there
  30. // will be an unaccounted offset of 2px when in quirksmode
  31. var rect = elem.getBoundingClientRect();
  32. return {
  33. left: Math.round(rect.left) - docElem.clientLeft,
  34. right: Math.round(rect.right) - docElem.clientLeft,
  35. top: Math.round(rect.top) - docElem.clientTop,
  36. bottom: Math.round(rect.bottom) - docElem.clientTop
  37. };
  38. }
  39. module.exports = getElementRect;