【发布时间】: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