В моем примере после каждого .container стоит <div style="height: 1000px"></div>, показывающий то, что в этой области у навигации .nav должен быть убран класс .active
|
между блоками .container - другие блоки, которые как раз таки и убирают класс .active у навигации.
|
и класс .active нужно добавлять не к .container , а к .nav !)))
|
Цитата:
<nav class="nav"></nav>
<section class="container" style="height: 250px; background: green"></section>
<div style="height: 1000px"></div>
<section class="container" style="height: 250px; background: yellow"></section>
<div style="height: 1000px"></div>
<section class="container" style="height: 250px; background: blue"></section>
<div style="height: 1000px"></div>
<style>
nav {
background: red;
position: fixed;
top: 0;
left: 0;
height: 50px;
width: 100%;
z-index: 1;
}
.active {
opacity: 0.25;
}
</style>
<script>
const navHeight = document.querySelector('nav').offsetHeight;
window.addEventListener('scroll', function () {
document.querySelectorAll('.container').forEach(function (node) {
const rect = node.getBoundingClientRect();
if (rect.y >= -rect.height && rect.y <= navHeight) {
node.classList.add('active');
} else {
node.classList.remove('active');
}
});
});
</script>
|
зачем ты добавляешь .active к блоку .container? я же написала, что .active надо добавлять к .nav ))
|
Чтобы получилось в итоге так:
<style>
.nav{
background: red;
}
.nav.active{
background: blue;
}
</style>
|
scroll добавление класса при пересечении блоков
webgraph,
при условии строки 21 top: 0;
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<nav class="nav"></nav>
<section class="container" style="height: 250px; background: green"></section>
<div style="height: 1000px"></div>
<section class="container" style="height: 250px; background: yellow"></section>
<div style="height: 1000px"></div>
<section class="container" style="height: 250px; background: blue"></section>
<div style="height: 1000px"></div>
<style>
nav {
background-color: red;
position: fixed;
top: 0;
left: 0;
height: 50px;
width: 100%;
z-index: 1;
}
.nav.active{
background-color: blue;
}
</style>
<script>
const nav = document.querySelector('nav');
const navHeight = nav.offsetHeight;
const boxs = Array.from(document.querySelectorAll('.container'));
const navAddCls = () => {
const add = boxs.some(box => {
const rect = box.getBoundingClientRect();
const y = rect.bottom / (navHeight + rect.bottom - rect.top);
return y > 0 && y < 1;
})
nav.classList.toggle('active', add)
}
window.addEventListener('scroll', navAddCls);
navAddCls()
</script>
</body>
</html>
|
воооо!!)) превосходно!)) великая благодарность тебе! )) потрясающий код! гениально))
|
| Часовой пояс GMT +3, время: 11:25. |