【问题标题】:Javascript HTML: how to get element's position relative to its parent? [duplicate]Javascript HTML:如何获取元素相对于其父元素的位置? [复制]
【发布时间】:2021-05-06 05:52:10
【问题描述】:

如何获取元素相对于其父元素的位置(左和上)?

注意:父position 既不是relative 也不是absolute,所以offsetLeftoffsetTop 不起作用。

父/子可能有边距/边框/填充。

只有 Vanilla JS,没有 jquery。

【问题讨论】:

标签: javascript html


【解决方案1】:

您可以使用.getBoundingClientRect() 返回元素相对于视口的位置。因此,您可以使用.getBoundingClientRect() 获取元素和父元素的位置,并从中计算元素相对于父元素的位置。看看下面的答案。

Element's coordinates relative to its parent

【讨论】:

  • 是自动计算父母的margin/border/padding吗?
  • 它计算高度/宽度=高度/宽度+填充。查看文档。 Element.getBoundingClientRect()
  • 我测试过 (clientRect.top - parentRect.top) 仅适用于没有边框和填充的父级。边框和填充的宽度改变了结果。是的,我可以获取边框/填充宽度。有没有更简单的方法?
  • 更新:孩子的边框和内边距也在改变结果
【解决方案2】:

您可以通过 window.getComputedStyle 和 vanilla js 选择器获取样式。

function getStyleProp(elem, prop){
    if(window.getComputedStyle)
        return window.getComputedStyle(elem, null).getPropertyValue(prop);
    else if(elem.currentStyle) return elem.currentStyle[prop]; //IE
}


elem = document.getElementById("id")
console.log(getStyleProp(elem, "top"))
console.log(getStyleProp(elem, "left"))

Rob W写的原创函数

src:Read CSS property of an element using JavaScript

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    相关资源
    最近更新 更多