How to get an DOM Element [x,y] coordinates in javascript? Specifically, the coordinates of a butto开发者_JAVA技巧n inside a scrollbox.
I found this offsetLeft attribute:
var elements = scroll.children; // with 12 children
if (!elements.item(2)) {
print("no element");
}
else if (!elements.item(2).offsetLeft) {
print("no attribute");
}
else {
print(elements.item(2).offsetLeft);
}
but it's printing "no attribute"...
By the way, it's for Mozilla environment.
Try something like this:
// Based on code from http://www.quirksmode.org/js/findpos.html
function FindElementDocumentPosition(element) {
var left = 0;
var top = 0;
var lastElement = element;
if (element.offsetParent) {
left += element.offsetLeft;
top += element.offsetTop;
element = element.offsetParent;
while (element) {
left += element.offsetLeft;
top += element.offsetTop;
left -= element.scrollLeft;
top -= element.scrollTop;
lastElement = element;
element = element.offsetParent;
}
}
// Adjust for document scroll position
var agent = navigator.userAgent.toLowerCase();
if (!PageInStandardsMode() || (agent.indexOf('firefox') == -1)) {
var leftAdjust = document.body.scrollLeft || document.documentElement.scrollLeft;
var topAdjust = document.body.scrollTop || document.documentElement.scrollTop;
left += leftAdjust;
top += topAdjust;
}
return {
x: left,
y: top
};
}
精彩评论