首页 > 解决方案 > 使用交叉点观察器制作动画

问题描述

当我的页面元素在视图中时,我一直在尝试为它们设置动画。我必须承认我是一个 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>

<!-- ... -->

标签: javascripthtmlcssintersection-observer

解决方案


因此,根据您提供的更多信息,相同代码无法在您的机器上运行的原因是<script>标签的放置。当放置在<head>文档中时,脚本中的代码会在 DOM 准备好之前直接执行:这意味着您的所有选择器都将undefined在运行时返回。

同时,在 StackOverflow 上使用的代码片段中,您粘贴的任何 JS 都被注入到<body>元素的末尾(这暗示了可能的解决方案,见下文)。

有两种方法可以解决此问题:

  1. <script>标签移动到<body>元素的末尾。这样,当 JS 被评估时,DOM 已经被解析并准备好了。
  2. 将所有 JS 逻辑包装在DOMContentLoaded事件触发后调用的函数中

推荐阅读