如何改变固定按钮,以改变BG的颜色,如果它的滚动部分具有相同的颜色?



基本上,我有固定的按钮底部滚动的页面在移动设备上。按钮的颜色是黄色的,我想当按钮在与按钮相同颜色的部分上滚动时,获得额外的类或直接内联更改样式,并将BG颜色设置为白色。观察者或类似的东西有可能吗?谢谢!

在这种情况下尝试使用Intersection Observer API的麻烦是双重的:

  1. 黄色部分不是按钮的祖先,它们可能是兄弟姐妹。

交集观察者API提供了一种异步观察目标元素与祖先元素交集变化的方法…

  1. 按钮是position: fixed,它不能很好地发挥与API的内部:交集观察者不工作的目标与位置:固定。

老式的方法是在每次滚动页面时检查按钮的边界框与黄色部分的边界框。

这意味着调用Element.getBoundingClientRect()一次为button(它的边界框应该永远不会改变,因为它是position: fixed相对于视口)和一次为每个黄色部分每次scroll事件引发。

下面是展示这种方法的示例:

const button = document.getElementById('some-action');
const buttonRect = button.getBoundingClientRect();

const yellowDivs = document.querySelectorAll('div.yellow');
const areIntersecting = (bounds1, bounds2) => 
bounds1.top < bounds2.bottom && bounds1.bottom > bounds2.top;
document.addEventListener('scroll', () => {
/* Use for...of, not .forEach so we can
return early. */
for (let item of yellowDivs) {
const itemRect = item.getBoundingClientRect();

if (areIntersecting(itemRect, buttonRect)) {
button.classList.add('white');
button.classList.remove('yellow');

/* We don't care how many yellow divs the button
is intersecting. Once we've found one, we can
return so we're not computing the rectangles
of the rest. */
return;    
}

/* If none of the yellow divs were interecting,
reset the color of the button. */
button.classList.add('yellow');
button.classList.remove('white');
}
});
div.blue, div.white, div.yellow { height: 250px; }
.blue { background-color: blue; }
.white { background-color: white; }
.yellow { background-color: yellow; }
#some-action {
position: fixed;
top: 20px;
right: 20px;
padding: 10px 20px;
}
<div class="blue"></div>
<div class="yellow"></div>
<div class="white"></div>
<div class="blue"></div>
<div class="yellow"></div>
<div class="white"></div>
<div class="blue"></div>
<div class="yellow"></div>
<div class="white"></div>
<div class="blue"></div>
<div class="yellow"></div>
<div class="white"></div>
<div class="blue"></div>
<div class="yellow"></div>
<div class="white"></div>
<button id="some-action" class="yellow">Some Action</button>

最新更新