当元素到达某一点时更改背景颜色(滚动)(响应)



对不起,伙计们,我对Javascript很陌生。在这里发帖之前,我已经搜索过类似的解决方案。

我想改变背景颜色,每次有多个div标签,带有特定的id,在到达浏览器顶部之前达到150像素。我希望它能在不同的设备上正确工作。我在javascript中尝试了不同的东西,但没有一个能给我想要的响应能力。当我减少浏览器的宽度时,文本是折叠的,div/ids的位置也会改变。因此,我的逻辑是……例如,如果一个div的id为";一个";距离顶部150像素,请更改背景颜色。

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(){ft_onscroll()};

在这个功能中,您可以获得当前的滚动位置。将它与你的元素位置进行比较,做你想做的事。

one_y = one.getBoundingClientRect().top;
function ft_onscroll(){
y = window.scrollY;
if(one_y > y){
//change background color 
}
}

我做到了。我的最终代码是这样的。也许我会把它缩短。

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");
}
}

最新更新