首页 > 解决方案 > 当元素到达某个点时更改背景颜色(滚动)(响应式)

问题描述

对不起,我对 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>

我在想这个,但它不起作用。

标签: htmltagsresponsivebackground-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");
  }
}


推荐阅读