简体   繁体   English

如何不使用JQuery来获得标签的左上角?

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

如何不使用JQuery来获得标签的左上角?

element.offsetLeft and element.offsetTop will get you the top let corner relevant to its parent element.offsetLeftelement.offsetTop将为您提供与其父级相关的顶部拐角

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. 递归调用它直到您遇到文档(document.parentNode为null并结束递归)将使您相对于整个文档。 Be wary that this isn't compatible with iframe or anything else that has its own document. 请注意,这与iframe或其他具有自己文档的文件不兼容。

[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. 您可以改为遍历offsetParent,但这也会引起一些问题。

This solution seems to work reasonably, but I havnt tested it thoroughly myself 这个解决方案似乎工作合理,但我自己已经对其进行了全面测试

Retrieve the position (X,Y) of an HTML element 检索HTML元素的位置(X,Y)

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: 现在您可以像这样使用它,向左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. 您可以像使用getRelativePos函数一样使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM