Created
September 28, 2013 07:08
-
-
Save xyqfer/6739399 to your computer and use it in GitHub Desktop.
getBoundingClientRect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getElementLeft(elem) { | |
var left = elem.offsetLeft, | |
current = elem.offsetParent; | |
while (current) { | |
left += current.offsetLeft; | |
current = current.offsetParent; | |
} | |
return left; | |
} | |
function getElementTop(elem) { | |
var top = elem.offsetTop, | |
current = elem.offsetParent; | |
while (current) { | |
top += current.offsetTop; | |
current = current.offsetParent; | |
} | |
return top; | |
} | |
function getBoundingClientRect(elem) { | |
var scrollTop = document.documentElement.scrollTop + document.body.scrollTop, | |
scrollLeft = document.documentElement.scrollLeft + document.body.scrollLeft; | |
if (document.getBoundingClientRect) { | |
if (typeof arguments.callee.offset !== "number") { | |
var temp = document.createElement("div"); | |
temp.style.cssText = "position: absolute; top: 0; left: 0;"; | |
document.body.appendChild(temp); | |
arguments.callee.offset = -temp.getBoundingClientRect().top - scrollTop; | |
document.body.removeChild(temp); | |
temp = null; | |
} | |
var rect = elem.getBoundingClientRect(), | |
offset = arguments.callee.offset; | |
return { | |
left: rect.left + offset, | |
right: rect.right + offset, | |
top: rect.top + offset, | |
bottom: rect.bottom + offset | |
}; | |
} else { | |
var offsetLeft = getElementLeft(elem), | |
offsetTop = getElementTop(elem); | |
return { | |
left: offsetLeft - scrollLeft, | |
right: offsetLeft - scrollLeft + elem.offsetWidth, | |
top: offsetTop - scrollTop, | |
bottom: offsetTop - scrollTop + elem.offsetHeight | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment