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

问题描述

对不起,我对Java语言很陌生。在这里发布之前,我已经搜索了类似的解决方案。

我想更改背景颜色,每次具有特定ID的多个div标签在到达浏览器顶部之前达到150像素。我希望它可以在不同的设备中正常工作。我在javascript中尝试了不同的方法,但没有一个给我想要的响应能力。当我减小浏览器的宽度时,文本会折叠,并且div / id的位置也会改变。因此,我的逻辑是...例如,如果id为“ One”的div距顶部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");
  }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...