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

其他回答

您可以将两个财产添加到Element.protype中,以获得任何元素的顶部/左侧。

Object.defineProperty( Element.prototype, 'documentOffsetTop', {
    get: function () { 
        return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
    }
} );

Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
    get: function () { 
        return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
    }
} );

这被称为:

var x = document.getElementById( 'myDiv' ).documentOffsetLeft;

下面是一个将结果与jQuery的offset().top和.left进行比较的演示:http://jsfiddle.net/ThinkingStiff/3G7EZ/

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

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

如果您只想在javascript中完成,这里有一些使用getBoundingClientRect()的单行程序

window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y

window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X

第一行将返回offsetTop,比如相对于文档的Y。第二行将返回offsetLeft,比如相对于文档的X。

getBoundingClientRect()是一个javascript函数,它返回元素相对于窗口视口的位置。

这样怎么样,通过传递元素的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。