Странное поведение Intersection Observer API | Не фиксирует видимый блок
Даже если два блока видно, в консоли показывается только один элемент. Что странно, только при старте скрипта он показывает два элемента сразу, при прокрутке только один и никак больше.
const options = {
threshold: 1.0
}
const targets = document.querySelectorAll('.blocks .block');
const value = document.querySelector('p b');
const callback = (entries, observer) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
console.log(entry.target.innerHTML);
value.innerHTML = entry.target.innerHTML;
});
}
const observer = new IntersectionObserver(callback, options);
targets.forEach(target => observer.observe(target));
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
line-height: 1;
font-family: sans-serif;
}
.container {
display: flex;
}
.container p {
font-size: 16px;
width: 50%;
padding: 10px;
}
.container .blocks {
width: 50%;
max-height: 100vh;
overflow: auto;
}
.container .blocks .block {
margin: 10px 0;
height: 35vh;
background-color: rgba(0, 0, 0, 0.25);
}
<div class="container">
<p>Value: <b></b></p>
<div class="blocks">
<div class="block">[1] block</div>
<div class="block">[2] block</div>
<div class="block">[3] block</div>
<div class="block">[4] block</div>
<div class="block">[5] block</div>
<div class="block">[6] block</div>
</div>
</div>