开发者

How to get top left corner of tag not using JQuery?

开发者 https://www.devze.com 2023-01-28 19:32 出处:网络
How to get to开发者_如何学Cp left corner of tag not using JQuery?element.offsetLeft and element.offsetTop will get you the top let corner relevant to its parent

How to get to开发者_如何学Cp left corner of tag not using JQuery?


element.offsetLeft and element.offsetTop will get you the top let corner relevant to its parent

function top(el) {
    var topVal = el.offsetTop;
    if (el.parentNode) topVal+= top(el.parentNode);
    return topVal;
}

function left(el) {
    var leftVal = el.offsetLeft;
    if (el.parentNode) leftVal+= left(el.parentNode);
    return leftVal;
}

calling it recursively up until you hit the documment (document.parentNode is null and ends rescursion) will get you it relative to the entire document. Be wary that this isn't compatible with iframe or anything else that has its own document.

[Edit]

The above recursive function is far too naive and only works on very simple pages. You can iterate over offsetParent instead but that also causes some issues.

This solution seems to work reasonably, but I havnt tested it thoroughly myself

Retrieve the position (X,Y) of an HTML element


To get the position relative to its parent, use this:

function getRelativePos(el) {
  var left=el.offsetX;
  var top=el.offsetY;
  return {top:top,left:left};
}

And now you can use it like this, alerting the left pos:

var myElement=document.getElementById('myel');
alert( getRelativePos(myElement).left );

If you want the absolute position, use this:

function getAbsPos(el) {
   var rect=el.getBoundingClientRect();
   return {top:rect.top,left:rect.left};
}

You can use it just like the getRelativePos function.

0

精彩评论

暂无评论...
验证码 换一张
取 消