Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用querySelectorAll的交叉点观察者抛出类型错误_Javascript_Html_Intersection Observer - Fatal编程技术网

Javascript 使用querySelectorAll的交叉点观察者抛出类型错误

Javascript 使用querySelectorAll的交叉点观察者抛出类型错误,javascript,html,intersection-observer,Javascript,Html,Intersection Observer,我遇到了一个十字路口观察员的问题。使用document.querySelectorAll('.entry')抛出一个类型错误:“未捕获的类型错误:未能在'IntersectionObserver'上执行'observe':参数1不是'Element'类型。” 更改document.querySelectorAll('.entry')到文档.querySelector('.entry')解决了这个问题,并且可以正常工作 我做错了什么 基本HTML结构: <html> <body&

我遇到了一个十字路口观察员的问题。使用
document.querySelectorAll('.entry')
抛出一个类型错误:“未捕获的类型错误:未能在'IntersectionObserver'上执行'observe':参数1不是'Element'类型。”

更改
document.querySelectorAll('.entry')
文档.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>
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);

出现此问题的原因是,您只能观察一个
targetElement
,但使用时传递的节点列表表示与指定选择器组匹配的文档元素列表。因此,您对它有一个问题,但只会给您第一个匹配的元素,因此在使用它时没有问题

您可以通过循环列表中的所有元素并单独观察每个元素来解决此问题,如下所示:

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

所以,现在我在尝试执行时遇到另一个错误:
blogs.classList.add('entry-animation')。我收到一个错误“无法读取未定义的属性'add'。我相信这是因为const“blogs”在函数中不可用?你将如何解决这个问题?谢谢,很简单。试试:
blogs.forEach(blog=>blog.classList.add('entry-animation')我相信这是在所有博客中添加类,并且它们同时具有动画效果,但是我们离它越来越近了@palash,您对如何防止同时添加所有类有何见解?当页面刷新时,所有类名为
entry
的div都会同时加载
entry动画。交叉口观察者正在同时触发所有事件。请原谅我的无知,谢谢你的帮助!请为此创建一个新问题,以便我们可以一次针对一个问题,并在此处发布问题链接。如果我以后有时间的话,我会设法调查的。此外,如果可能的话,在这个问题上添加一个小演示。如果你能用一个简单的演示重现一个问题,你会得到更多的回答。