Javascript 为什么相交观测者在第一个元素相交时向所有观察到的元素添加类?
请原谅我的无知,因为我正在学习。我正在使用Javascript 为什么相交观测者在第一个元素相交时向所有观察到的元素添加类?,javascript,html,css,animation,intersection-observer,Javascript,Html,Css,Animation,Intersection Observer,请原谅我的无知,因为我正在学习。我正在使用.entry类获取divs,通过向它们添加.entry animation类,在与交点观察者相交时设置动画 我以前从未使用过选择所有元素和设置动画。在第一个交点上,所有元素同时设置动画。我做错了什么 这是演示: body { background: #FFF; } .entry { background: #f6f6f6; text-align: center; padding: 5%; margin: 5%; border:
.entry
类获取div
s,通过向它们添加.entry animation
类,在与交点观察者相交时设置动画
我以前从未使用过选择所有元素和设置动画。在第一个交点上,所有元素同时设置动画。我做错了什么
这是演示:
body {
background: #FFF;
}
.entry {
background: #f6f6f6;
text-align: center;
padding: 5%;
margin: 5%;
border: 1px solid #ccc;
border-radius: 15px;
box-shadow: 0 4px 5px #cecece;
}
.entry-animation {
animation: 2s fadeIn-1;
animation-fill-mode: both;
}
@keyframes fadeIn-1 {
0% {
transform: translateY(20%);
opacity: 0;
}
100%{
transform: translateY(0);
opacity:1;
}
}
const options = {
threshold: 0.4,
};
const blogs = document.querySelectorAll('.entry');
const observer = new IntersectionObserver(function(entries, observer) {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
return;
}
blogs.forEach(blog => blog.classList.add('entry-animation'));
},options);
});
blogs.forEach(blog => observer.observe(blog));
这是HTML:
<div id="content-container">
<div class="content">
<div class="entry">
<h2>
Title of Post 1
</h2>
<p>
Some content here on each entry
</p>
</div>
<div class="entry">
<h2>
Title of Post 2
</h2>
<p>
Some content here on each entry
</p>
</div>
<div class="entry">
<h2>
Title of Post 3
</h2>
<p>
Some content here on each entry
</p>
</div>
<div class="entry">
<h2>
Title of Post 4
</h2>
<p>
Some content here on each entry
</p>
</div>
<div class="entry">
<h2>
Title of Post 5
</h2>
<p>
Some content here on each entry
</p>
</div>
<div class="entry"></div>
</div>
</div>
这是JS:
body {
background: #FFF;
}
.entry {
background: #f6f6f6;
text-align: center;
padding: 5%;
margin: 5%;
border: 1px solid #ccc;
border-radius: 15px;
box-shadow: 0 4px 5px #cecece;
}
.entry-animation {
animation: 2s fadeIn-1;
animation-fill-mode: both;
}
@keyframes fadeIn-1 {
0% {
transform: translateY(20%);
opacity: 0;
}
100%{
transform: translateY(0);
opacity:1;
}
}
const options = {
threshold: 0.4,
};
const blogs = document.querySelectorAll('.entry');
const observer = new IntersectionObserver(function(entries, observer) {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
return;
}
blogs.forEach(blog => blog.classList.add('entry-animation'));
},options);
});
blogs.forEach(blog => observer.observe(blog));
您可以通过替换以下内容轻松解决此问题:
blogs.forEach(blog => blog.classList.add('entry-animation'));
与
在条目内部。forEach()
循环。这里的问题基本上是我们只需要使用entry.target
将动画类添加到视图中的元素中,而不是一次将它们添加到所有元素中
啊,当然。谢谢你的帮助,保持安全!很高兴它对你有帮助,对你也一样!