在我的示例中,如果我的窗口顶部位置距离底部约100px,我会尝试淡入/淡出元素overlay
。
怎么可以这样做?
.section-card{
position: relative;
height: 500px;
line-height: 500px;
text-align: center;
font-size: 46px;
color: #fff;
background: #777;
}
.section-card:nth-child(2) {
background: #666;
}
.section-card:nth-child(3) {
background: #555;
}
.section-card:nth-child(4) {
background: #444;
}
.section-card:nth-child(5) {
background: #333;
}
.overlay{
pointer-events: none;
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
visibility: hidden;
background-color: #000;
opacity: 0;
}

<div class="section-card">
1
<div class="overlay"></div>
</div>
<div class="section-card">
2
<div class="overlay"></div>
</div>
<div class="section-card">
3
<div class="overlay"></div>
</div>
<div class="section-card">
4
<div class="overlay"></div>
</div>
<div class="section-card">
5
<div class="overlay"></div>
</div>
&#13;
答案 0 :(得分:0)
你想要实现的目标可以这样做。
var overlays = document.querySelectorAll('.overlay');
var totalOverlays = overlays.length;
var overlayToChange = overlays[totalOverlays - 1];
document.addEventListener('scroll', function(){
var fromBottom = document.body.offsetHeight - (window.innerHeight + window.scrollY);
if(fromBottom <= 100){
overlayToChange.style.opacity = 0.5;
overlayToChange.style.visibility='visible'
}else{
overlayToChange.style.opacity = 0;
overlayToChange.visibility='hidden';
}
});
.section-card{
position: relative;
height: 500px;
line-height: 500px;
text-align: center;
font-size: 46px;
color: #fff;
background: #777;
}
.section-card:nth-child(2) {
background: #666;
}
.section-card:nth-child(3) {
background: #555;
}
.section-card:nth-child(4) {
background: #444;
}
.section-card:nth-child(5) {
background: #333;
}
.overlay{
pointer-events: none;
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
visibility: hidden;
background-color: #000;
opacity: 0;
width: 100%;
height: 100%;
transition: opacity .5s ease-out;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Overlays</title>
</head>
<body>
<div class="section-card">
1
<div class="overlay"></div>
</div>
<div class="section-card">
2
<div class="overlay"></div>
</div>
<div class="section-card">
3
<div class="overlay"></div>
</div>
<div class="section-card">
4
<div class="overlay"></div>
</div>
<div class="section-card">
5
<div class="overlay"></div>
</div>
</body>
</html>