javascript - 使用交叉点观察器制作动画
问题描述
当我的页面元素在视图中时,我一直在尝试为它们设置动画。我必须承认我是一个 Javascript 初学者,我在互联网上找到的所有代码片段也不起作用。我的代码到底有什么问题?
编辑:我刚刚注意到我的代码在将其作为片段添加到此处时正在运行。我正在使用 chrome 上的 index.html 文件,我的样式表肯定是正确链接的。我找不到什么问题。为什么它在这里工作,但不在我的浏览器上?是因为我忘记添加堆栈溢出代码运行程序自动添加的内容吗?
const options = {
root: null,
rootMargin: '0px',
threshold: 0.5
}
let callback = (entries) => {
entries.forEach(entry => {
if(entry.isIntersecting) {
entry.target.classList.add('isVisible');
} else {
entry.target.classList.remove('isVisible');
}
});
}
let observer = new IntersectionObserver(callback, options);
document.querySelectorAll('.box')
.forEach(box => { observer.observe(box) });
section {
width: 100%;
height: 500px;
padding: 50px;
box-sizing: border-box;
display: flex;
justify-content: center;
align-items: center;
}
div {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
width: 80%;
height: 80%;
}
.box {
opacity: 0;
transform: translateY(40px);
transition: all 1s ease-in-out;
}
.box.isVisible {
opacity: 1;
transform: translateY(0);
}
<!-- ... -->
<section>
<div class="box">
<h2>
Lorem ipsum dolor sit amed
</h2>
</div>
</section>
<section>
<div class="box">
<h2>
Lorem ipsum dolor sit amed
</h2>
</div>
</section>
<section>
<div class="box">
<h2>
Lorem ipsum dolor sit amed
</h2>
</div>
</section>
<section>
<div class="box">
<h2>
Lorem ipsum dolor sit amed
</h2>
</div>
</section>
<section>
<div class="box">
<h2>
Lorem ipsum dolor sit amed
</h2>
</div>
</section>
<!-- ... -->
解决方案
因此,根据您提供的更多信息,相同代码无法在您的机器上运行的原因是<script>
标签的放置。当放置在<head>
文档中时,脚本中的代码会在 DOM 准备好之前直接执行:这意味着您的所有选择器都将undefined
在运行时返回。
同时,在 StackOverflow 上使用的代码片段中,您粘贴的任何 JS 都被注入到<body>
元素的末尾(这暗示了可能的解决方案,见下文)。
有两种方法可以解决此问题:
- 将
<script>
标签移动到<body>
元素的末尾。这样,当 JS 被评估时,DOM 已经被解析并准备好了。 - 将所有 JS 逻辑包装在
DOMContentLoaded
事件触发后调用的函数中
推荐阅读
- javascript - 在滚动 React Native Animated 上做动画但闪烁
- java - 使生成代码的自定义 Gradle 任务在 IDE 导入时运行
- ios - 如何在 UIContainerView 内导航
- google-cast - Android 开始投射到从自定义投射对话框中选择的设备
- django - 带有两个外键的 Django 查询
- android - 寻呼机指示器颤动
- java - 是否可以调用本机查询并将结果集存储在非实体对象中?
- c# - 在 Windows 10 IoT Core 上访问 USB 端口
- angular - 以 angular6 形式排除输入 formControlName
- excel - 如何在 Excel 中使用两个过滤器提取数据?