我正在看一个关于 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
}
原文由 Joheb 发布,翻译遵循 CC BY-SA 4.0 许可协议
该元素返回 null,因为脚本在解析 HTML 之前运行。我在我的脚本标签中使用了 defer 来避免这个问题。