我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。


当前回答

我接受了@meouw的回答,添加到允许边界的clientLeft中,然后创建了三个版本:

getAbsoluteOffsetFromBody-类似于@meouw,它获取相对于文档的body或html元素的绝对位置(取决于quicks模式)

getAbsoluteOffsetFromGivenElement-返回相对于给定元素的绝对位置(relativeEl)。注意,给定的元素必须包含元素el,否则其行为将与getAbsoluteOffsetFromBody相同。如果在另一个(已知)元素中包含两个元素(可选地,节点树上的多个节点),并且希望使它们处于相同的位置,则这非常有用。

getAbsoluteOffsetFromRelative-返回相对于具有position:relative的第一个父元素的绝对位置。这与getAbsoluteOffsetFromGivenElement类似,原因相同,但仅限于第一个匹配元素。

getAbsoluteOffsetFromBody = function( el )
{   // finds the offset of el from the body or html element
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
    {
        _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
        _y += el.offsetTop - el.scrollTop + el.clientTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}

getAbsoluteOffsetFromGivenElement = function( el, relativeEl )
{   // finds the offset of el from relativeEl
    var _x = 0;
    var _y = 0;
    while( el && el != relativeEl && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
    {
        _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
        _y += el.offsetTop - el.scrollTop + el.clientTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}

getAbsoluteOffsetFromRelative = function( el )
{   // finds the offset of el from the first parent with position: relative
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
    {
        _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
        _y += el.offsetTop - el.scrollTop + el.clientTop;
        el = el.offsetParent;
        if (el != null)
        {
            if (getComputedStyle !== 'undefined')
                valString = getComputedStyle(el, null).getPropertyValue('position');
            else
                valString = el.currentStyle['position'];
            if (valString === "relative")
                el = null;
        }
    }
    return { top: _y, left: _x };
}

如果您仍然有问题,特别是与滚动有关的问题,您可以尝试查看http://www.greywyvern.com/?post=331-我注意到getStyle中至少有一段有问题的代码,假设浏览器运行正常,这段代码应该是不错的,但根本没有测试其他代码。

其他回答

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

offsetLeft
offsetTop

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

IE和FF3具有

clientLeft
clientTop

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

这很简单,在JS中有两行:

var elem = document.getElementById("id");    
alert(elem.getBoundingClientRect());

我接受了@meouw的回答,添加到允许边界的clientLeft中,然后创建了三个版本:

getAbsoluteOffsetFromBody-类似于@meouw,它获取相对于文档的body或html元素的绝对位置(取决于quicks模式)

getAbsoluteOffsetFromGivenElement-返回相对于给定元素的绝对位置(relativeEl)。注意,给定的元素必须包含元素el,否则其行为将与getAbsoluteOffsetFromBody相同。如果在另一个(已知)元素中包含两个元素(可选地,节点树上的多个节点),并且希望使它们处于相同的位置,则这非常有用。

getAbsoluteOffsetFromRelative-返回相对于具有position:relative的第一个父元素的绝对位置。这与getAbsoluteOffsetFromGivenElement类似,原因相同,但仅限于第一个匹配元素。

getAbsoluteOffsetFromBody = function( el )
{   // finds the offset of el from the body or html element
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
    {
        _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
        _y += el.offsetTop - el.scrollTop + el.clientTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}

getAbsoluteOffsetFromGivenElement = function( el, relativeEl )
{   // finds the offset of el from relativeEl
    var _x = 0;
    var _y = 0;
    while( el && el != relativeEl && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
    {
        _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
        _y += el.offsetTop - el.scrollTop + el.clientTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}

getAbsoluteOffsetFromRelative = function( el )
{   // finds the offset of el from the first parent with position: relative
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
    {
        _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
        _y += el.offsetTop - el.scrollTop + el.clientTop;
        el = el.offsetParent;
        if (el != null)
        {
            if (getComputedStyle !== 'undefined')
                valString = getComputedStyle(el, null).getPropertyValue('position');
            else
                valString = el.currentStyle['position'];
            if (valString === "relative")
                el = null;
        }
    }
    return { top: _y, left: _x };
}

如果您仍然有问题,特别是与滚动有关的问题,您可以尝试查看http://www.greywyvern.com/?post=331-我注意到getStyle中至少有一段有问题的代码,假设浏览器运行正常,这段代码应该是不错的,但根本没有测试其他代码。

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