【发布时间】: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 文件头部的
-
您的脚本标签在
<head>标签中:这就是问题所在。当 DOM 尚未准备好时,您的 JS 正在执行。你的控制台说什么?你应该遇到过一些警告。 -
哇非常感谢您的帮助!在阅读我们的答案之前,我要睡觉了,还不如尝试最后一次尝试,它奏效了!我将脚本标签放在正文标签的末尾,就在结束的
标签: javascript html css intersection-observer