使用 querySelectorAll 的 Intersection Observer 抛出 TypeError

Intersection Observer using querySelectorAll throws a TypeError

我被 Intersection Observer 问题卡住了。使用 document.querySelectorAll('.entry') 会引发类型错误:"Uncaught TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'."

document.querySelectorAll('.entry'); 更改为 document.querySelector('.entry'); 解决了问题并且有效。

我做错了什么?

基本HTML结构:

<html>
<body>
  <div id="content-container">
    <div class="content">
      <div class="entry">Some content here on each entry</div>
      <div class="entry"></div>
      <div class="entry"></div>
      <div class="entry"></div>
      <div class="entry"></div>
      <div class="entry"></div>
    </div>
</div>
</body
</html>

JavaScript:

const blog = document.querySelectorAll('.entry');
const options = {
  root: null,
  rootMargin: '0px',
};

const observer = new IntersectionObserver(function(entries, observer) {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) {
      return;
    } 

    else {
      console.log(entry);
    }
  });



}, options);


observer.observe(blog);

出现这个问题是因为 IntersectionObserver.observe() can only observe one targetElement but using document.querySelectorAll() you are passing a NodeList representing a list of the document's elements that match the specified group of selectors. Thus you are having an issue with it, but document.querySelector() 只给你第一个匹配的元素,所以当你使用它时没有问题。

您可以通过遍历列表中的所有元素并分别观察每个元素来解决此问题,例如:

const blogs = document.querySelectorAll('.entry');
blogs.forEach(blog => observer.observe(blog));