具有视差效果的滚动性能优化

Optimization of scrolling performance with parallax effect

我有一个包含两个部分的页面,它们相互堆叠。上半部分有一个固定位置的背景图像,以产生视差效果。因为我在滚动时遇到了严重的性能问题,所以我不得不更改布局。

来自:

.upper-section {

    height: 100vh;

    background: url("./img/background.png") no-repeat fixed;
    background-size: cover;
}

.lower-section { 
    height: 100vh;
    ...
}

对此:

.upper-section {

    height: 100vh;

    overflow: hidden; // added for pseudo-element
    position: relative; // added for pseudo-element

    &::before {
        content: ' ';
        display: block;
        position: fixed; // instead of background-attachment
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background: url("./img/background.png") no-repeat fixed;
        background-size: cover;
        will-change: transform; // creates a new paint layer
        z-index: -1;
    }
}

将背景放在它自己的容器中。我的问题是我的背景图像容器没有继承上部容器的高度并且也覆盖了下部。如果我将 position: fixed; 更改为 position: absolute;,我会遇到与以前相同的性能问题。知道如何解决这个问题吗?

更新 1

致所有未来的读者:我通过将下方部分的背景设置为白色来解决我的问题:

.lower-section { 
    height: 100vh;
    background: white;
}

根据您的尝试和@MrLister 建议回答问题:

如前所述,在评论流中迷路了,您在 .lower-section 上缺少背景以隐藏之前的背景。

html,
body {
  margin: 0
}

.upper-section {
  height: 100vh;
  overflow: hidden;
  position: relative;
}

.upper-section::before {
  content: ' '; 
  position: fixed; 
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: url("http://lorempixel.com/700/700") no-repeat fixed;
  background-size: cover;
  will-change: transform;  
  z-index: -1;
}

.lower-section {
  height: 100vh;
  background: white;
}
<div class="upper-section">
  Upper section
</div>

<div class="lower-section">
  Lower section
</div>