Find X/Y of an HTML element with JavaScript
This question already has an answer here:
以下是我的做法:
// Based on: http://www.quirksmode.org/js/findpos.html
var getCumulativeOffset = function (obj) {
var left, top;
left = top = 0;
if (obj.offsetParent) {
do {
left += obj.offsetLeft;
top += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
x : left,
y : top
};
};
That can be tricky depending on browser and version. I would suggest using jQuery and the positions plugin.
You can use a library such as Prototype or jQuery, or you can use this handy function:
It returns an array.
myPos = findPos(document.getElementById('something'))
x = myPos[0]
y = myPos[1]
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
链接地址: http://www.djcxy.com/p/15598.html
上一篇: 获得元素位置的确切方法是什么?