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



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

我有一个所需结果的视频示例:https://bcx-production-attachments-us-west-2.s3-us-west-2.amazonaws.com/99ccd694-7e7d-11ea-940f-a0369f08283c?AWSAccessKeyId=AKIAIXJK7HJ33HYQWMEQ&过期=1587420147&签名=zhLi2pKSDMHFWCcbtAZE7f5Gz5k%3D&响应内容处置=inline%3B%20filename%3D%22视差%20示例.mp4%22%3B%20 filename%2A%3D-UTF-8%27视差%2520示例.mp4&响应内容类型=视频%2mp4

我对视差的理解是,当以下元素滚动"经过"它时,图像保持固定。在视频中,当"透明部分"容器滚动经过它时,背景图像似乎是视差,就像视差的行为一样。但另一方面,图像本身在标题下向上滚动。

我一直在玩,似乎没能达到这个结果。思考视差如何与背景附着一起工作:固定,我似乎无法将我的大脑包裹在如何实现这一点上。我的视差图像不会在标题下向上滚动,而是保持不变。到目前为止,我只是在做纯css,不确定是否需要Javascript。

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

此外:页眉保持固定,直到它遇到"透明部分"容器的顶部,然后它与页面的其余部分一起滚动。视差图像以较慢的速度滚动。如果这很重要的话,可以单独列出细节。

编辑:

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

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中获取类,并删除了cssbackground-attachment: fixed属性,因为它没有在这种不同的视差技术中使用。

在行动中看到它:https://codepen.io/jguitarz/pen/WNQGYQB