在其上的特定div上更改固定背景图像



当我尝试制作一个"我们的故事"时section,当我滚动时,它的div会向上移动当特定的div出现在中间时,背景图片会改变。我想要一个固定的背景图像。当div移动到中间时,可以很容易地改变背景图片。背景图和div是相关的

我还在学习如何设计样式,我不能正确地创建它。

我已经包含了一个参考链接,所以你可以看到我的目标。

参考:https://webflow.com/made-in-webflow/website/Change-Background-Image-on-Scroll

.parent {
background-image: url(https://picsum.photos/1080/1920);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
height: 300vh;
text-align: center;
color: white;
}
.div1{
background-color: aqua;
height: 50vh;
margin-top: 90vh;
padding: 20px;
width: 400px;
margin: 90px auto
}
.div2{
background-color: skyblue;
height: 50vh;
padding: 20px;
width: 400px;
margin: 90px auto
}
.div3{
background-color: grey;
height: 50vh;
margin-top: 90vh;
padding: 20px;
width: 400px;
margin: 90px auto
}
<div class="parent">
<div class="div1" >
Content about desert
</div>
<div class="div2" >
Content about mountains
</div>
<div class="div3" >
Content about birds
</div>
</div>

下面的代码是一个大概的示例。它应该给你一个开始的实验,以及在WWW上查找的东西。

var sections;
const backgrounds = [
"url(https://i.picsum.photos/id/604/1080/1920.jpg?hmac=ZGdArZ8jNmfX3SDYlQMsYeGsKy6b_1uBH2WGFt3wYzk)",
"url(https://i.picsum.photos/id/301/1080/1920.jpg?hmac=7cyfS0iaSux6TVm9Wnkg4vtXIWyg_YyhhWYHM6yUTnE)",
"url(https://i.picsum.photos/id/155/1080/1920.jpg?hmac=UZT1atpRomcjj2ijIjwR9C3DY0xtD4On3m5XMNLak6o)"
];
var parent;
var bottomOffset;
function getViewScrollingElements() {
parent = document.getElementById("parent");
sections = document.getElementsByClassName("section");
bottomOffset = window.getComputedStyle(parent).getPropertyValue("height");
bottomOffset = parseInt(bottomOffset.substr(0, bottomOffset.length - 2)) / 3;
//  Do first check before a scroll could have occured
checkInView();
}
function checkInView () {
var boundingRect;
for ( var i = 0; i < sections.length; i++ ) {
//  Get the extremities of the div
boundingRect = sections[i].getBoundingClientRect();
//  Are the div's extremities in view
if ( boundingRect.top < window.innerHeight && boundingRect.bottom >= bottomOffset ) {
parent.style.backgroundImage = backgrounds[i];
break;  //  Only want one at a time
}
}
}
.background {
background-size: cover;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
}
.parent {
text-align: center;
color: white;
height: 100%;
overflow-y: auto;
}
.section {
height: 70vh;
padding: 20px;
width: 400px;
margin: 90px auto;
opacity: 85%;
}
.section:nth-of-type(1) {
background-color: aqua;
}
.section:nth-of-type(2) {
background-color: skyblue;
}
.section:nth-of-type(3) {
background-color: grey;
}
<body onLoad="getViewScrollingElements()">
<div class="background"></div>
<div id="parent" class="parent" onScroll="checkInView()">
<div class="section">
Content about desert
</div>
<div class="section">
Content about mountains
</div>
<div class="section">
Content about birds
</div>
</div>
</body>

它不喜欢iframes,因为它不会在SOs fiddler中正常运行,但在Chrome和Firefox中工作。

最新更新