Finding the offset client position of an element

余生长醉 提交于 2019-12-10 09:55:21

问题


How to find the offset client position of an element using Javascript? (I assume the same code can be written in a BHO or Gecko/NPAPI).

The problem I am facing is a way to find out the offset client position of the element. The e.srcElement.offsetX/Y does not give the correct value always (same goes for clientX/Y). In some cases we also need to consider the parent element scroll.

How do we do this in general? Is there an easy way for this?


回答1:


function getElementTop ( Elem ) 
{
    var elem;

    if ( document.getElementById ) 
    {   
        elem = document.getElementById ( Elem );
    } 
    else if ( document.all ) 
    {
        elem = document.all[Elem];
    }           

    yPos = elem.offsetTop;
    tempEl = elem.offsetParent;

    while ( tempEl != null ) 
    {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }  

    return yPos;
}   


function getElementLeft ( Elem ) 
{
    var elem;

    if ( document.getElementById ) 
    {
        var elem = document.getElementById ( Elem );
    } 
    else if ( document.all )
    {
        var elem = document.all[Elem];
    }           

    xPos = elem.offsetLeft;
    tempEl = elem.offsetParent;         

    while ( tempEl != null ) 
    {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }           
    return xPos;
}

Pass the element id to the functions.




回答2:


See the code below:

function getOffsetSum(elem) {
    var top=0, left=0;
    while(elem) {
        top = top + parseInt(elem.offsetTop);
        left = left + parseInt(elem.offsetLeft);
        elem = elem.offsetParent;
    }
    return {top: top, left: left};
}



回答3:


To include scrolling, take a look at this jQuery event listener to log the scrollTop and the offset.

// Don't put this in the scroll event listener callback, or that will be unnecessarily performance intensive.
var offset = $("#id").offset().top;

$(window).bind("scroll", function() {

 console.log(
  $(window).scrollTop() + 
  offset
 );

});

To get the offset alone,

("#id").offset().top;



回答4:


CoffeeScript version of Orhun Alp Oral's answer:

getOffset = (elem)->
    top = 0
    left = 0
    while elem
        top += parseInt(elem.offsetTop)
        left += parseInt(elem.offsetLeft)
        elem = elem.offsetParent
    {top, left}


来源:https://stackoverflow.com/questions/1409355/finding-the-offset-client-position-of-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!