跨浏览器修复 - 位置:固定为转换元素的后代

Cross-browser fix - position: fixed as descendants of transformed elements

如描述here and discussed in this chromium bug report according to W3C spec

In the HTML namespace, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.

position: fixed 是除 none 之外具有 transform 的任何元素的后代都相对于该元素。


但是 IE <= 11 和至少 FF36 的 Firefox 不符合规范,而是相对于视口定位元素(如最初预期的那样)。

是否有任何修复("polyfill")以在所有浏览器中获得相同的行为?

否则有没有办法 "feature detect" 而不是浏览器检测此行为来交替设置受影响元素的样式?

我不知道有任何 "polyfills" 可以在这种情况下强制跨浏览器保持一致性,因此,由于它在问题中作为可接受的替代方案提出,我将提供关于 "feature detection".

您可以通过创建几个临时元素来测试浏览器是否符合规范,一个嵌套在另一个元素中。使用translatey()将父元素从"natural"的位置下移,固定子元素的positiontop值为0。然后,通过使用 getBoundingClientRect(),我们可以检查子元素的 top 是否等于父元素的 - 如果是,则浏览器符合规范。

var body=document.body,
    div=document.createElement("div"),
    span=document.createElement("span"),
    compliant;
div.style.transform="translatey(100px)";
span.style.position="fixed";
span.style.top=0;
div.appendChild(span);
body.appendChild(div);
compliant=span.getBoundingClientRect().top===div.getBoundingClientRect().top;
body.removeChild(div);
console.log(compliant);