javascript - 使用 Intersection Observer 切换活动类
问题描述
我试图在滚动页面时更改我的部分的活动类。我正在使用intersectionObserver,但我感觉很坚持。我需要从 activeId 获取 activeElement,但不确定如何执行此操作。
这是我得到的解码代码:
const options = {
threshold: 0.75
}
let observer = new IntersectionObserver(check, options);
function check(entries) {
entries.forEach(entry => {
const activeId = entry.target.id;
const activeElement =
if(entry.isIntersecting){
activeElement.classList.toggle("your-active-class");
};
});
};
sections.forEach(section => {
observer.observe(section);
});
解决方案
entry.isIntersecting
直接用于您的第二classList.toggle()
个(布尔)参数。- 使用 options
{threshold: 0}
,或者根本不使用,因为threshold默认为0
const check = (entries) => entries.forEach(entry => {
entry.target.classList.toggle("is-active", entry.isIntersecting);
});
const Obs = new IntersectionObserver(check);
document.querySelectorAll("section").forEach(el => Obs.observe(el));
* {margin:0; box-sizing: border-box;}
section {
min-height: 100vh;
transition: 0.5s;
transform: scale(0.4);
display: flex;
justify-content: center;
align-items: center;
font-size: 70vh;
}
.is-active {
transform: scale(1);
}
<section style="background: #0bf;">1</section>
<section style="background: #f0b;">2</section>
<section style="background: #fb0;">3</section>
<section style="background: #0fb;">4</section>
推荐阅读
- sed - sed 脚本未在 Vagrantfile 中执行
- animation - 在 ThreeJS 中使用 KeyFrameTracks 同时动画立方体
- r - 如何使用时间序列滑块过滤数据
- python - 使用 Python 一次在文件夹中的多个文件上运行 perl 脚本
- java - 如何检索已存储在 firebase 数据库中并显示在回收站视图中的图像?
- python - 在“ Pipenv”中定义shell入口点的规范方法?
- xcode - 如何从零开始在 Xcode 中创建准系统“Hello World”项目?
- python - How can I iterate a dictionary which is into another dictionary to get specific values?
- html - 从网页中提取和选择链接
- java - Graphics2d Rotation 旋转所有对象