【发布时间】: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