【问题标题】:Animating with Intersection Observer使用交叉点观察器制作动画
【发布时间】:2021-10-31 21:05:34
【问题描述】:

我一直在尝试为页面中的元素设置动画。我必须承认我是一个 Javascript 初学者,我在互联网上找到的所有代码 sn-ps 也不起作用。我的代码到底有什么问题?

编辑:我刚刚注意到我的代码在将其添加为 sn-p 时正在工作。我正在使用 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>

<!-- ... -->

【问题讨论】:

  • 如果代码在这里有效,但在您的本地项目中无效,那么问题不在于代码本身。检查您的浏览器网络选项卡:是否正确加载了 JS 和 CSS 文件?您是否正确清除缓存?
  • 是的,我清除了缓存,JS 链接在 html 文件头部的
  • 您的脚本标签在&lt;head&gt; 标签中:这就是问题所在。当 DOM 尚未准备好时,您的 JS 正在执行。你的控制台说什么?你应该遇到过一些警告。
  • 哇非常感谢您的帮助!在阅读我们的答案之前,我要睡觉了,还不如尝试最后一次尝试,它奏效了!我将脚本标签放在正文标签的末尾,就在结束的

标签: javascript html css intersection-observer


【解决方案1】:

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

与此同时,在 StackOverflow 上使用的代码 sn-p 中,您粘贴的任何 JS 都被注入到 &lt;body&gt; 元素的末尾(这暗示了可能的解决方案,见下文)。

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

  1. &lt;script&gt; 标记移动到&lt;body&gt; 元素的末尾。这样,当 JS 被评估时,DOM 已经被解析并准备好了。
  2. 将所有 JS 逻辑包装在一个函数中,该函数在 DOMContentLoaded event 被触发后调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多