【发布时间】:2021-12-25 20:37:02
【问题描述】:
我正在与交叉点观察者一起玩,以创建一个无限滚动的狗网站。当您滚动并出现 6 只狗时,一个 api 会再触发 6 次以抓取更多狗以添加到 DOM。我希望狗在用户滚动时加载,但是当已经查看过的狗离开视口并在页面上上升时,该元素会从页面上删除。所以狗总是在向下滚动时加载,但向上滚动时你总是在页面的顶部。我当前在名为lastFunc 的函数中的实现导致它的行为非常奇怪。怎样才能达到想要的效果。
class CardGenerator {
constructor() {
this.$cardContainer = document.querySelector('.card-container');
this.$allCards = undefined;
this.observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
entry.target.classList.toggle('show', entry.isIntersecting);
if (entry.isIntersecting) {
this.observer.unobserve(entry.target);
}
});
},
{
threshold: 1,
rootMargin: '150px',
}
);
this.loadNewCards();
}
cacheDOMElements() {
this.$allCards = document.querySelectorAll('.card');
}
loadNewCards() {
for (let index = 0; index < 6; index++) {
fetch('https://dog.ceo/api/breeds/image/random', { method: 'GET' })
.then((result) => {
return result.json();
})
.then((r) => {
console.log(r);
const card = document.createElement('div');
card.classList.add('card');
const imageElement = document.createElement('img');
imageElement.classList.add('forza-img');
imageElement.setAttribute('src', r.message);
card.appendChild(imageElement);
this.observer.observe(card);
this.$cardContainer.append(card);
this.cacheDOMElements();
if (this.$allCards.length % 6 === 0) this.lastFunc();
});
}
}
lastFunc() {
console.log(this.$allCards);
if (this.$allCards.length > 12) {
this.$allCards.forEach((item, idx) => {
if (idx < 6) {
item.remove();
}
});
}
this.$allCards.forEach((card, idx) => {
this.observer.observe(card);
});
const lastCardObserver = new IntersectionObserver((entries) => {
const $lastCard = entries[0];
if (!$lastCard.isIntersecting) return;
this.loadNewCards();
lastCardObserver.unobserve($lastCard.target);
});
lastCardObserver.observe(document.querySelector('.card:last-child'));
}
}
const cardGenerator = new CardGenerator();
html,
body {
height: 100%;
width: 100%;
box-sizing: border-box;
padding: 0;
margin: 0;
}
.card {
float: left;
width: 48vw;
margin: 1%;
transform: translateX(100px);
opacity: 0;
transition: 150ms;
}
.card.show {
transform: translateY(0);
opacity: 1;
}
.card img {
width: 100%;
border-radius: 15px;
height: 30vh;
object-fit: cover;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Dog Random Images</h1>
<div class="card-container"></div>
</body>
<script src="app.js" ></script>
</html>
【问题讨论】:
标签: javascript intersection-observer