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

发布于 2024-10-06 11:27:41 字数 27 浏览 0 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

避讳 2024-10-13 11:27:41

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;
}

递归调用它,直到您点击文档(document.parentNode 为 null 并结束递归) )将为您提供相对于整个文档的信息。请注意,这与 iframe 或任何其他拥有自己文档的内容不兼容。

[编辑]

上面的递归函数太幼稚了,只适用于非常简单的页面。您可以改为迭代 offsetParent,但这也会导致一些问题。

这个解决方案似乎工作合理,但我自己还没有彻底测试它

检索 HTML 元素的位置 (X,Y)

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

你与清晨阳光 2024-10-13 11:27:41

要获取相对于其父级的位置,请使用:

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

现在您可以像这样使用它,提醒左侧位置:

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

如果您想要绝对位置,请使用:

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

您可以像 getRelativePos 功能。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文