我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。
当前回答
获取div相对于左侧和顶部的位置
var elm = $('#div_id'); //get the div
var posY_top = elm.offset().top; //get the position from top
var posX_left = elm.offset().left; //get the position from left
其他回答
如果页面至少包含任何“DIV”,meouw给出的函数会将“Y”值抛出到当前页面限制之外。为了找到准确的位置,您需要处理offsetParent和parentNode。
尝试以下代码(检查FF2):
var getAbsPosition = function(el){
var el2 = el;
var curtop = 0;
var curleft = 0;
if (document.getElementById || document.all) {
do {
curleft += el.offsetLeft-el.scrollLeft;
curtop += el.offsetTop-el.scrollTop;
el = el.offsetParent;
el2 = el2.parentNode;
while (el2 != el) {
curleft -= el2.scrollLeft;
curtop -= el2.scrollTop;
el2 = el2.parentNode;
}
} while (el.offsetParent);
} else if (document.layers) {
curtop += el.y;
curleft += el.x;
}
return [curtop, curleft];
};
此函数返回元素相对于整个文档(页面)的位置:
function getOffset(el) {
const rect = el.getBoundingClientRect();
return {
left: rect.left + window.scrollX,
top: rect.top + window.scrollY
};
}
使用此选项,我们可以获得X位置:
getOffset(element).left
…或Y位置:
getOffset(element).top
这样怎么样,通过传递元素的ID,它将返回左侧或顶部,我们还可以组合它们:
1) 查找左侧
function findLeft(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return rec.left + window.scrollX;
} //call it like findLeft('#header');
2) 查找顶部
function findTop(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return rec.top + window.scrollY;
} //call it like findTop('#header');
或3)找到左侧和顶部
function findTopLeft(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return {top: rec.top + window.scrollY, left: rec.left + window.scrollX};
} //call it like findTopLeft('#header');
如果使用jQuery,维度插件非常出色,可以让您精确地指定所需内容。
e.g.
相对位置,绝对位置,无填充的绝对位置,有填充。。。
继续下去,让我们说你可以用它做很多事情。
另外,使用jQuery的好处是它的文件大小很小,使用起来很方便,以后如果没有它,就不会返回JavaScript。
如果您使用jQuery,这可能是一个简单的解决方案:
<script>
var el = $("#element");
var position = el.position();
console.log( "left: " + position.left + ", top: " + position.top );
</script>