我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。
当前回答
经过大量研究和测试,这似乎奏效了
function getPosition(e) {
var isNotFirefox = (navigator.userAgent.toLowerCase().indexOf('firefox') == -1);
var x = 0, y = 0;
while (e) {
x += e.offsetLeft - e.scrollLeft + (isNotFirefox ? e.clientLeft : 0);
y += e.offsetTop - e.scrollTop + (isNotFirefox ? e.clientTop : 0);
e = e.offsetParent;
}
return { x: x + window.scrollX, y: y + window.scrollY };
}
看见http://jsbin.com/xuvovalifo/edit?html,js,输出
其他回答
HTML程序,用于显示通过将鼠标拖到元素上,您就复制了它并自己使用它<!DOCTYPE html><html><head><标题>元素的位置</title><!-- scropt获取位置--><script type=“text/javascript”>函数getPositionXY(元素){var rect=元素.getBoundingClientRect();document.getElementById('text').innerHTML='X:'+rect.X+'<br>'+'Y:'+direct.Y;}</script></head><body><p>将鼠标移到文本上</p><div onmouseover=“getPositionXY(this)”>职位:<p id=“text”></p></div></body></html>
由于不同的浏览器以不同的方式呈现边框、填充、边距等。我编写了一个小函数来检索每个根元素中特定元素的顶部和左侧位置,您需要精确的维度:
function getTop(root, offset) {
var rootRect = root.getBoundingClientRect();
var offsetRect = offset.getBoundingClientRect();
return offsetRect.top - rootRect.top;
}
对于检索左侧位置,必须返回:
return offsetRect.left - rootRect.left;
jQuery.offset()将获取第一个元素的当前坐标,或者设置匹配元素集合中每个元素相对于文档的坐标。
获取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
如果您只想在javascript中完成,这里有一些使用getBoundingClientRect()的单行程序
window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y
window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X
第一行将返回offsetTop,比如相对于文档的Y。第二行将返回offsetLeft,比如相对于文档的X。
getBoundingClientRect()是一个javascript函数,它返回元素相对于窗口视口的位置。