gpt4 book ai didi

javascript - 滚动时改变不透明度

转载 作者:行者123 更新时间:2023-11-30 07:54:31 25 4
gpt4 key购买 nike

我的目标是在向下滚动时更改 DIV 的不透明度。顺利过渡很重要!

  • 当body的scrollTop为400时,Test-div的不透明度应为1。
  • 当body的scrollTop为800时,Test-div的opacity应该为0。

这是我目前拥有的,但它不起作用。

window.addEventListener('scroll', function() {
if (document.body.scrollTop > 400) {
var currScrollPos2 = document.body.scrollTop;
document.getElementById('test').style.opacity = -currScrollPos2 / 400 + 2;
}
}
};
* {
margin: 0;
padding: 0;
}

body {
height: 2000px;
width: 100%;
}

#test {
width: 200px;
height: 200px;
background-color: red;
position: fixed;
}
<div id="test"></div>

最佳答案

你很接近,但是 body.scrollTop 属性 does not work in all browsers .

我冒昧地稍微清理了您的标记和代码。例如,您在 JavaScript 的末尾缺少一个右括号。您的 CSS 标记中还有一些多余的规则,我已将其删除。

var test = document.getElementById('test');
window.addEventListener('scroll', function(e) {
// http://stackoverflow.com/a/28633515/962603
var scroll = window.pageYOffset || document.documentElement.scrollTop ||
document.body.scrollTop || 0;
test.style.opacity = Math.max(0, Math.min(1, -scroll / 400 + 2));
});
* {
margin: 0;
padding: 0;
}

body {
height: 2000px;
}

#test {
position: fixed;
width: 200px;
height: 200px;
background-color: red;
}
<div id="test"></div>

关于javascript - 滚动时改变不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com