首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >利用视差效应优化滚动性能

利用视差效应优化滚动性能
EN

Stack Overflow用户
提问于 2017-08-05 19:22:25
回答 1查看 749关注 0票数 0

我有一个页面,有两个部分堆叠在一起。上面的部分具有固定位置的背景图像,以创建视差效果。因为我在滚动时遇到了大量的性能问题,所以我不得不改变布局。

从这个开始:

代码语言:javascript
复制
.upper-section {

    height: 100vh;

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

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

要这样做:

代码语言:javascript
复制
.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

致所有未来的读者:我通过将下半部分的背景设置为白色修复了我的问题:

代码语言:javascript
复制
.lower-section { 
    height: 100vh;
    background: white;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-05 21:07:35

从您的尝试,并建议@先生MrLister给出一个问题的答案:

正如前面评论和在评论流中丢失的,你在.lower-section上遗漏了一个背景来隐藏之前的背景。

代码语言:javascript
复制
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;
}
代码语言:javascript
复制
<div class="upper-section">
  Upper section
</div>

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45521323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档