繁体   English   中英

滚动时如何正确设置固定背景?

[英]How to properly set a fixed background while scrolling?

所以我有以下 PageLayout.jsx 用于设置我所有页面的布局:

   export function PageLayout({ children }) {
      return (
        <div
          style={{
            height: "100vh",
            backgroundImage: "url(" + background + ")",
            backgroundSize: "cover",
            backgroundAttachment: "fixed",
          }}
        >
          <NavBar />

          {children}
          
          <Footer />
        </div>
      );
    }

我希望背景是固定图像,但在用户滚动时不移动(当页面变为可滚动时)。 换句话说,我只希望页面中的元素看起来好像在滚动。

图像确实看起来是固定的,但是,当您滚动时,图像会在超出初始页面的高度时被切断。 我知道这与我的子组件溢出代码中显示的父 div 的事实有关。 但是,我不能简单地设置“溢出:自动”,因为无论出于何种原因导致浏览器滚动条消失在我的“固定:顶部”导航栏后面。 关于设置固定背景图像的正确方法的任何想法?

在这里,您只需要一个与具有图像但具有overflow-y: scroll

 body { margin: 0; }.background { height: 100vh; width: 100vw; background-image: url("https://lh3.googleusercontent.com/2hDpuTi-0AMKvoZJGd-yKWvK4tKdQr_kLIpB_qSeMau2TNGCNidAosMEvrEXFO9G6tmlFlPQplpwiqirgrIPWnCKMvElaYgI-HiVvXc=w600"); background-size: "cover"; background-clip: fixed; }.container { height: 100%; width: 100%; overflow-y: scroll; }.thing { height: 33%; background-color: rgba(0, 0, 255, 0.288); }
 <div class="background"> <div class="container"> <h1 class="thing">Thing 1</h1> <h1 class="thing">Thing 2</h1> <h1 class="thing">Thing 3</h1> <h1 class="thing">Thing 4</h1> <h1 class="thing">Thing 5</h1> <h1 class="thing">Thing 6</h1> </div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM