【发布时间】:2021-03-25 15:04:47
【问题描述】:
如果你看到了糟糕的标题,但仍然想帮忙回答这个问题,非常感谢。
我受到这个网站marussiabeverages.com 的启发,尝试根据滚动位置操作一些 CSS。就像网站一样,我想在用户向下滚动时淡出固定背景。
我附上了一个我现在拥有的示例:不透明度设置为零并随着更多.hero 的滚动而增加,从而导致效果淡入。基本上,我想反转它,使不透明度从 1 开始,并随着页面滚动而减小。
这感觉就像我缺少一个明显的答案,但我的逻辑并不好。再次感谢!
奖励:我注意到如果滚动太快,浏览器不会计算每个像素。这对我在这里所做的事情并不是非常重要,但如果你知道如何解决这个问题,请告诉我。
document.addEventListener("DOMContentLoaded", function() {
function fade() {
const BG_HERO = document.querySelector(".bg-hero");
const HERO = document.querySelector(".hero");
const DEMO = document.querySelector(".demo");
let height = HERO.offsetHeight;
let position = document.documentElement.scrollTop;
let o = position / height;
let opacity = o.toFixed(2);
if (position <= height) {
BG_HERO.style.opacity = opacity;
DEMO.innerHTML =
`
Position / Height: ${position} / ${height}
<br>
Opacity: ${BG_HERO.style.opacity}
`;
}
}
document.addEventListener("scroll", function() {
fade();
});
});
.hero {
height: 600px;
}
.bg-hero {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: url(https://picsum.photos/1920/1080) bottom center no-repeat;
background-size: cover;
opacity: 0;
}
.demo {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%,-50%);
background: #000;
color: #fff;
}
<div class="bg-hero"></div>
<div class="hero">Scroll Me!</div>
<div style="height: 999px;">
<p class="demo"><p>
【问题讨论】:
标签: javascript css opacity