Intersection Observer 不确认点击时添加的新项目

问题描述 投票:0回答:1

我有一组正在运行动画的项目。单击按钮后,将添加更多具有相同类别的项目。这些物品将以 4 件为一组添加。

起初,交叉口观察者会忽略新项目,但如果我再次单击按钮,它们就会起作用。

有趣的是,我的代码按照我的示例中的预期工作,但在我正在处理的页面上却没有,该页面使用相同的基本结构,以及该部分的确切 JS (https://remaxnews-preprod.js)。 go-vip.net/category/买家-卖家/)

对该页面上的问题可能是什么有什么想法吗?

const options = {
    threshold: 0.6
};

const sectionObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('enter');
            observer.unobserve(entry.target);
        }
    });
}, options);

// Convert NodeList to an array
let reveal = Array.from(document.querySelectorAll('.post-list-card'));

// Initial observation for existing items
reveal.forEach(section => {
    sectionObserver.observe(section);
});

// Update reveal with all .post-list-card items
function updateReveal() {
    const updatedSections = document.querySelectorAll('.post-list-card');
    reveal = Array.from(updatedSections); // Update the reveal array
    reveal.forEach(newSection => {
            sectionObserver.observe(newSection); // Observe new items
    });
}

const loadMore = document.querySelector('.post-list .fusion-load-more-button');
loadMore.addEventListener('click', updateReveal);

/* this is not part of the code. added just for demonstration purposes */
function addNewCards() {
            const contentDiv = document.querySelector('.content');
            for (let i = 0; i < 4; i++) {
                const newCard = document.createElement('div');
                newCard.classList.add('post-list-card');
                newCard.textContent = 'New Card'; // You can customize the content here
                contentDiv.appendChild(newCard);
            }
        }
.post-list-card{
  width: 100%;
  height: 50px;
  margin: 50px 0;
  padding: 50px;
  background: blue;
  color: yellow;
}

.post-list-card.enter{
  background: red;
  color: #fff;
}
<div class="post-list">
  <div class="content">
    <div class="post-list-card">Card</div>
    <div class="post-list-card">Card</div>
    <div class="post-list-card">Card</div>
    <div class="post-list-card">Card</div>
   </div>
   <button class="fusion-load-more-button" onclick="addNewCards()">Load More</button>
</div>

javascript click loading intersection-observer
1个回答
0
投票

我想通了。问题是脚本在加载 js 之前运行。我无法更改主题中代码的顺序,因此我在单击运行代码时添加了延迟。

// Update reveal with all .post-list-card items
function updateReveal() {
    setTimeout(function() {
      const updatedSections = document.querySelectorAll(".post-list-card");
      reveal = Array.from(updatedSections); // Update the reveal array
      reveal.forEach((newSection) => {
          sectionObserver.observe(newSection); // Observe new items
      });
  },800);
}
© www.soinside.com 2019 - 2024. All rights reserved.