【问题标题】:Why doesn't getComputedStyle take into account margin collapsing?为什么 getComputedStyle 不考虑边距折叠?
【发布时间】:2013-04-25 11:37:45
【问题描述】:

关于浏览器内的 Javascript,window.getComputedStyle() 方法应该给出应用于元素的 CSS 属性的最终使用值。根据MDN documentation,这意味着“在所有计算都已执行之后”。

但是,“所有计算”似乎不包括边距折叠。在 Firefox 和 Chrome 中(至少),指令 getComputedStyle().marginBottom 在计算任何边距折叠之前返回计算值。

例如,考虑以下元素:

<div style="margin: 10px 0 15px 0"></div>

它的顶部和底部边距将被折叠,因为(大致)其内容高度为零(参见the W3C CSS2 Recommendation)。 CSSOM 方法将返回这些值:

getComputedStyle().marginTop → 10px
getComputedStyle().marginBottom → 15px
getBoundingClientRect().top → {top of margin box} + marginTop
getBoundingClientRect().bottom → idem top

但是,由于边距折叠,布局在边界客户矩形之前显示了 10px 的边距,之后显示了 5px 的边距,即max(0, marginBottom - marginTop)

getComputedStyle().marginBottom为什么不直接返回5px,即“所有计算完成后”的实际使用值,而不是指定的15px?这是 W3C 推荐的行为吗? (我在 w3.org 文档中没有看到任何关于此的内容。)

这是错误还是功能?

【问题讨论】:

    标签: javascript css cssom


    【解决方案1】:

    计算的使用的值是有区别的。此外,getComputedStyle() 返回 resolved 值,“可能是计算值或使用值”。 MDN reference.

    至于很多计算状态的实用价值,我不知道。

    【讨论】:

      【解决方案2】:

      我没有看到你所有的代码,但我认为函数名实际上是“getComputedStyle”,带有一个“u”。

      错字?能这么容易吗?你不会是第一个——包括我自己。

      希望这会有所帮助。

      【讨论】:

      • 是的,这是一个错字。谢谢
      • 但问题仍然存在 ;-)
      猜你喜欢
      • 2015-12-26
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2017-07-27
      相关资源
      最近更新 更多