html - 当元素到达某个点时更改背景颜色(滚动)(响应式)
问题描述
对不起,我对 Javascript 很陌生。我在这里发布之前已经搜索了类似的解决方案。
我想更改背景颜色,每次具有特定 id 的多个 div 标签在到达浏览器顶部之前达到 150 像素。我希望它能够在不同的设备上正确工作。我在 javascript 中尝试了不同的东西,但都没有给我想要的响应能力。当我减小浏览器的宽度时,文本会折叠并且 div/ids 的位置会发生变化。所以,我的逻辑是......例如,如果 id="One" 的 div 距离顶部 150px,则更改背景颜色。
var one = document.getElementById("one");
var two = document.getElementById("two");
var three = document.getElementById("three");
window.addEventListener('scroll', () => {
if(one.getBoundingClientRect().top < 150){
document.body.addClass = "bg-one";
}
});
.site-main{
background-color: white;
}
.bg-one{
background-color: red;
}
.bg-two{
background-color: blue;
}
.bg-three{
background-color: yellow;
}
<body class="site-main" id="main">
<div id="one" class="">Text</div>
<div id="two" class="">Text</div>
<div id="three" class="">Text</div
</body>
我在想这个,但它不起作用。
解决方案
我做到了。我的最终代码是这样的。也许我会缩短它。
window.onscroll = function(){
fromTop_onscroll();
};
function fromTop_onscroll(){
var main = document.getElementById("main");
var one = document.getElementById("one");
one_distance = one.getBoundingClientRect().top; // distance from top
var two = document.getElementById("two");
two_distance = two.getBoundingClientRect().top; // distance from top
if(one_distance < 150 && two_distance > 150){
main.classList.add("bg-one");
main.classList.remove("site-main");
main.classList.remove("bg-two");
} else if (two_distance < 150 && one_distance < 0) {
main.classList.add("bg-two");
main.classList.remove("bg-one");
} else if (one_distance > 150 && two_distance > 150){
main.classList.add("site-main");
main.classList.remove("bg-two");
main.classList.remove("bg-one");
}
}
推荐阅读
- c# - .NET Core Web API 处理已发送响应后的异常
- javascript - Django - 如何拨打电话号码并一键打开表单页面?
- sql - 将数据格式从行更改为列
- c# - 在申请期间注册 CultureInfo
- javascript - javascript中el.classList.remove的时间复杂度是多少
- python - 如何通过 django 中的父表访问中间表字段?
- python - 在 python urlpatterns 中找不到 url 的反向
- java - 如何使用 div 标签/类从下拉列表中选择一个选项?.selenium
- bash - 通过 msmtp 运行时,Awk 权限被拒绝
- javascript - to 固定在 mongodb 中