Чтобы проверить, виден ли элемент, используйте API-интерфейс Intersection Observer . Этот API построен именно для этой цели и практически не требует вычислений, только проверка со значением isIntersecting
, чтобы увидеть, вошел ли элемент в представление.
IntersectionObserverIn использует функцию обратного вызова сделать что-то, когда элемент вошел или покинул вид. В этой функции вы можете указать, что должно произойти, когда это произойдет.
Я сделал фрагмент с примером того, как он работает и как вы можете его реализовать.
/**
* What to do when an item enters the screen
* If it is in the screen, isIntersecting will be true.
* Add a class when it is.
*/
const intersectionCallback = (entries) => {
for (const entry of entries) { // Loop over all elements that either enter or exit the view.
if (entry.isIntersecting) { // This is true when the element is in view.
entry.target.classList.add('show'); // Add a class.
}
}
}
/**
* Create a observer and use the instersectionCallback as
* the instructions for what to do when an element enters
* or leaves the view
*/
const observer = new IntersectionObserver(intersectionCallback);
/**
* Get all .item elements and loop over them.
* Observe each individual item.
*/
const items = document.querySelectorAll('.item');
for (const item of items) {
observer.observe(item);
}
.item {
display: flex;
align-items: center;
justify-content: center;
color: #fff;
height: 200px;
width: 100%;
margin-bottom: 20px;
opacity: 0;
transition: opacity 1s ease-out;
}
.item:nth-of-type(odd) {
background-color: #333;
}
.item:nth-of-type(even) {
background-color: #111;
}
.item.show {
opacity: 1;
}
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>