我想知道如何在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,输出

其他回答

获取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 

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>

大多数浏览器上的HTML元素将具有:-

offsetLeft
offsetTop

它们指定元素相对于其最近的具有布局的父元素的位置。通常可以通过offsetParent属性访问此父级。

IE和FF3具有

clientLeft
clientTop

这些财产不太常见,它们使用其父工作区指定元素位置(填充区是工作区的一部分,但边界和边距不是)。

要获得元素的总偏移量,可以递归地对所有父偏移量求和:

function getParentOffset(el): number {
if (el.offsetParent) {
    return el.offsetParent.offsetTop + getParentOffset(el.offsetParent);
} else {
    return 0;
}
}

使用该实用函数,dom元素的总顶部偏移量为:

el.offsetTop + getParentOffset(el);

此函数返回元素相对于整个文档(页面)的位置:

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