我可以有一个 div 有视差图像也显示视差图像向上滚动吗

Can I have a div that has a parallax image also show the parallax'd image scroll up

问题标题可能有点令人困惑,因为我不确定如何正确解释它。

我有一个所需结果的视频示例: https://bcx-production-attachments-us-west-2.s3-us-west-2.amazonaws.com/99ccd694-7e7d-11ea-940f-a0369f08283c?AWSAccessKeyId=AKIAIXJK7HJ33HYQWMEQ&Expires=1587420147&Signature=zhLi2pKSDMHFWCcbtAZE7f5Gz5k%3D&response-content-disposition=inline%3B%20filename%3D%22Parallax%20Example.mp4%22%3B%20filename%2A%3DUTF-8%27%27Parallax%2520Example.mp4&response-content-type=video%2Fmp4

我对视差的理解是当以下元素滚动时图像保持固定 'past'。在视频中,背景图像看起来是视差的,因为“透明部分”容器像视差行为一样滚动过去。但另一方面,图像本身在 header.[=15= 下向上滚动]

我一直在玩,似乎无法达到这个结果。考虑视差如何与 background-attachment: fixed 一起工作,我似乎无法思考如何实现这一点。我的视差图像不会在 header 下向上滚动,而是保持原样。到目前为止,我只是在做纯粹的 css,不确定是否需要 Javascript。

如果可能的话,我正在寻找一些见解,如果可能的话,我将如何获得这种外观。

另外:header 保持固定,直到它到达 'Transparent Section' 容器的顶部,然后它与页面的其余部分一起滚动。视差图像以较慢的速度滚动。如果重要,请单独详细说明。

编辑:

https://codepen.io/losttech/pen/wvKzYmX 这是我所拥有的代码笔,我无法实现像视频中那样向上滚动到 header 的视差图像。

HTML:

<div class="parallax-container">
  <div class="header-container">
    <header>
    <ul>
      <li>Menu 1</li>
      <li>Menu 3</li>
      <li>Menu 3</li>
    </ul>
  </header>
  </div>
  <div class="parallax-img-container">
    <div class="blurb">
      Transparent Section
    </div>
  </div>
</div>
<div class="body-content">
  <h2>Rest of the body content here...</h2>
</div>

CSS:

.parallax-container {
  height: 730px;
  position: relative;
}

.header-container {
  height: 550px;
  position: absolute;
  width: 100%;
  z-index: 99999;
}

header {
  width: 100%;
  background: grey;
  height: 80px;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
}

ul {
  display: flex;
  li {
    list-style: none;
    margin-right: 1rem;
  }
}

.parallax-img-container {
  height: 650px;
  background-image: url(https://wallpaperaccess.com//full/83991.jpg);
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  position: relative;
}

.blurb {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 100px;
  background: rgba(0,0,0,0.6);
  color: white;
  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.body-content {
  height: 500px;
}

是的,这种类型的视差需要一点 javascript。您需要做的是捕获滚动事件并根据用户滚动距离的一小部分更改背景位置。

这是我以前的做法:

const el = document.getElementsByClassName("parallax-img-container")[0];
window.addEventListener("scroll", () => {
  let offset = window.pageYOffset;
  //0.5 can be whatever you want it will adjust how far / fast the image appears to scroll
  el.style.backgroundPositionY = `${offset * 0.5}px`;
});

编辑:

我改进了 el 选择器以从您的 html 中获取 class 并删除了 css background-attachment: fixed 属性 因为它是未用于这种不同的视差技术。

查看实际效果:https://codepen.io/jguitarz/pen/WNQGYQB