Как у блока с position:fixed менять цвет при прохождении определенной границы?
Нужно чтобы при прокрутке страницы на синем фоне он был красным, а на красным был синим
.block {
width: 100%;
height: 200px;
}
.red {
background: red;
}
.blue {
background: blue;
}
.fixed {
position: fixed;
background: blue;
top: 100px;
left: 100px;
z-index: 10;
width: 80px;
height: 80px;
}
<body>
<div class="fixed"></div>
<div class="block red"></div>
<div class="block blue"></div>
<div class="block red"></div>
<div class="block blue"></div>
</body>
Ответы (2 шт):
Автор решения: Anton Shchyrov
→ Ссылка
function onScroll() {
const back = document.elementFromPoint(10, 100);
const className = (back.classList.contains('red')) ? 'blue' : 'red';
const fix = document.querySelector('.fixed');
if (!fix.classList.contains(className)) {
fix.classList.remove('red', 'blue');
fix.classList.add(className);
}
}
onScroll();
window.addEventListener('scroll', onScroll);
.block {
width: 100%;
height: 200px;
}
.red {
background: red;
}
.blue {
background: blue;
}
.fixed {
position: fixed;
top: 100px;
left: 100px;
z-index: 10;
width: 80px;
height: 80px;
}
<div id="container">
<div class="fixed"></div>
<div class="block red"></div>
<div class="block blue"></div>
<div class="block red"></div>
<div class="block blue"></div>
</div>
Автор решения: Anton Shchyrov
→ Ссылка
А вот решение с динамической границей
function onScroll() {
const fix = document.querySelector('.fixed');
const rectFix = fix.getBoundingClientRect();
const back = document.elementFromPoint(rectFix.x - 1, rectFix.y);
const rectBack = back.getBoundingClientRect();
const topHeight = rectBack.bottom - rectFix.y;
const backClass = (back.classList.contains('red')) ? 'red' : 'blue';
const otherClass = (backClass === 'red') ? 'blue' : 'red';
const fixTop = fix.querySelector('.top');
fixTop.style.height = (topHeight < rectFix.height) ? (topHeight + "px") : "100%";
if (!fixTop.classList.contains(otherClass)) {
fixTop.classList.remove('red', 'blue');
fixTop.classList.add(otherClass);
const fixBottom = fix.querySelector('.bottom');
fixBottom.classList.remove(otherClass);
fixBottom.classList.add(backClass);
}
}
onScroll();
window.addEventListener('scroll', onScroll);
.block {
width: 100%;
height: 200px;
}
.red {
background: red;
}
.blue {
background: blue;
}
.fixed {
position: fixed;
top: 100px;
left: 100px;
z-index: 10;
width: 80px;
height: 80px;
display: flex;
flex-direction: column;
}
.fixed .bottom {
flex-grow: 1;
}
<div id="container">
<div class="fixed">
<div class="top"></div>
<div class="bottom"></div>
</div>
<div class="block red"></div>
<div class="block blue"></div>
<div class="block red"></div>
<div class="block blue"></div>
</div>