未捕获的类型错误:无法在“IntersectionObserver”上执行“observe”:参数 1 不是“元素”类型

Joh*_*heb 5 javascript intersection-observer

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

<!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>
Run Code Online (Sandbox Code Playgroud)
const sectionOne = document.querySelector('.section1');

const options = {};

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

observer.observe(sectionOne);
Run Code Online (Sandbox Code Playgroud)
body{
    padding: 0;
    margin: 0;
}

section{
    height: 100vh;
    width:100%;
}
section:nth-child(odd){
    background: lightcoral
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*heb 11

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

<script src='script.js' defer></script>
Run Code Online (Sandbox Code Playgroud)