【发布时间】:2017-04-07 12:46:08
【问题描述】:
我正在尝试仅使用 CSS 而没有第三方库来创建视差滚动效果。使用background-attachment: fixed,我能够在页面上的多个全角 div 上实现我想要的效果。然而,使用它会对性能产生很大的负面影响。我改为将方法更改为找到 here 的方法:
.element {
overflow: hidden; // added for pseudo-element
position: relative; // added for pseudo-element
// Fixed-position background image
&::before {
content: ' ';
position: fixed; // instead of background-attachment
width: 100%;
height: 100%;
top: 0;
left: 0;
background: url('/path/to/img.jpg') no-repeat center center;
background-size: cover;
will-change: transform; // creates a new paint layer
z-index: -1;
}
}
我在一个 div 上使用了这种方法进行了尝试,效果非常好。然而,当我将它应用到其余部分时,背景全部重叠,我只看到其中一个(因为其余部分在它后面)。这显然是一个 z-index 问题,因为所有伪元素都是重叠的,但我想不出只有 CSS 的解决方案。
【问题讨论】:
标签: css scroll parallax fixed background-attachment