当div覆盖另一个div时,模拟颜色的变化

我有一个固定的div,它滚动某些元素。

当div超过某个div时,我不想拥有某种颜色和某个图像。 当它超过另一个div时,我希望它能改变颜色。

在此处输入图像描述

基本现场演示

我很确定为此我需要两个div,一个是隐藏的。

我玩z-index ,但这似乎不能用这些基本的东西来解决。

更复杂的例子。

我玩这个属性:

 .two { background-color: green; z-index: 250; } 

但订单看似矛盾,

如果两个尺寸都是固定的,我可以使用js来对与滚动的pic相关的元素的像素的高度做一些魔术。

有没有办法解决?

你几乎在考虑使用两个div。 诀窍是你需要在不同的容器中创建它们并依赖于overflow:hidden和使用position:absolute在这种情况下固定的position:absolute intead但你需要一些JS来控制位置,所以它的行为就像固定:

 window.onscroll = function() { var scroll = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop; document.documentElement.style.setProperty('--scroll-var', scroll+"px"); } 
 :root { --scroll-var:0; } .container { height: 150px; outline: 1px solid red; position: relative; overflow:hidden; } .fixed { position: absolute; top:var(--scroll-var,20px); } .only-one{ background-color: lightblue; } .only-two{ background-color: lightgreen; margin-top:-150px; /*The height of the previous section*/ } .overlay { position:absolute; width: 100%; height: 100% } .one { background-color: yellow; } .two { background-color: green; } 
 
  • a
  • b
  • c
  • a
  • b
  • c

如果您需要颜色来对背景颜色做出反应,可以使用mix-blend-mode

mix-blend-mode CSS属性描述元素的内容应如何与元素的直接父元素的内容和元素的背景混合。

注意: IE / Edge不支持

 .container { height: 150px; outline: 1px solid red; } .fixed { position: fixed; background-color: lightblue; mix-blend-mode: luminosity; } .one { background-color: yellow; } .two { background-color: green; } 
 
  • a
  • b
  • c

看一下这个 :

https://jsbin.com/wozedar/edit?html,css,js,output

或者更重要的是使用此函数作为您想要的基础:

 function isOnTopOf(a, b) { var fixedCoord = a.getBoundingClientRect(); var bgCoord = b.getBoundingClientRect(); if (fixedCoord.top + fixedCoord.height >= bgCoord.top) { return true; } return false; } 

要比较元素,在您的情况下,您可能会在每个滚动上执行以下操作:

 var fixed = document.querySelector(".fixed-div"); var div1 = document.querySelector(".div--1"); if (isOnTopOf(fixed, div2)) { fixed.classList.add("fixed-div--light"); } 

函数element.getBoundingClientRect()为您提供相关信息,您可以从中确定对象是在对象上方,下方还是彼此之上。

只需在窗口对象中添加一个事件监听器,然后比较每个卷轴上的位置,就可以了。 如果你想做更复杂的东西,你可以考虑限制滚动function,但这个jsbin应该让你去。