【问题标题】:Uncaught TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'未捕获的类型错误:无法在“IntersectionObserver”上执行“观察”:参数 1 不是“元素”类型
【发布时间】:2020-08-15 17:31:17
【问题描述】:

我正在观看 Intersection Observer 上的视频,我已经逐字复制了他的脚本,但不知何故我遇到了这个错误。有人遇到了同样的错误,但通过将 querySelectorAll 更改为 querySelector 解决了他们的问题。即使我复制了他们的代码并将其更改为 querySelector ,它仍然无法在我的最终工作。下面的代码是我的。我正在使用 vs code 实时服务器。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel='stylesheet' href='style.css'>
    <script src='script.js'></script>
</head>
<body>
    <section class = 'section1'></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
</body>
</html>
const sectionOne = document.querySelector('.section1');

const options = {};

const observer = new IntersectionObserver(function
(entries, observer){
    entries.forEach(entry => {
        console.log(entry);
    });
}, options);

observer.observe(sectionOne);
body{
    padding: 0;
    margin: 0;
}

section{
    height: 100vh;
    width:100%;
}
section:nth-child(odd){
    background: lightcoral
}

【问题讨论】:

  • querySelector 返回Element | null,因此您需要以某种方式断言该元素存在。例如尝试observer.observe(sectionOne!)observer.observe(assertExists(sectionOne))
  • 没有注意到元素出现为空。我在脚本标签中使用 defer 在脚本之前加载页面,以便元素可以存在

标签: javascript intersection-observer


【解决方案1】:

该元素返回 null,因为脚本在 HTML 被解析之前运行。我在脚本标签中使用了 defer 来避免这个问题。

<script src='script.js' defer></script>

【讨论】:

  • 使用 assertExists 会立即发现这个问题。很好的调试。
  • 难道没有一种自然的方法可以做到这一点……比如在整个窗口准备好时运行脚本?还是不相关?
【解决方案2】:

实际上你发布的例子看起来很好,你可以在我制作的这个 JSFiddle 中查看它:https://jsfiddle.net/sandro_paganotti/pomtng6f/3/

const sectionOne = document.querySelector('.section1');
const options = {};

const observer = new IntersectionObserver(function
 (entries, observer){
    entries.forEach(entry => {
       console.log(entry);
 });
}, options);

observer.observe(sectionOne);

当然,作为仅附加到第一部分的观察者,它只会在第一部分进入或离开视口时触发。

【讨论】:

    【解决方案3】:

    添加

    $(document).ready(function () { // your code }
    

    document = 你的 div。

    您必须确保 DOM 已加载,并且当它“准备好”时它会启动 :)。

    【讨论】:

      【解决方案4】:

      您的选择是第一个元素,因为 querySelector 采用第一个元素 如果要全选,请使用 querySelectorAll,然后循环遍历它们 观察者可以一一观察,应该是这样的:

      const sections = document.querySelectorAll('section');
      
      const options = {};
      
      const observer = new IntersectionObserver(function
      (entries, observer){
      entries.forEach(entry => {
          console.log(entry);
      });
      }, options);
      
      // loop 
      sections.forEach( section => {
      observer.observe(section);
      });
      

      【讨论】:

        猜你喜欢
        • 2021-02-08
        • 1970-01-01
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-20
        • 2021-05-06
        相关资源
        最近更新 更多