2 回答
TA贡献1911条经验 获得超7个赞
编辑:
根据IntersectionObserver api,我们不能调用 takeRecords,因为它在回调中为空(因为队列已刷新)(希望获取所有观察到的记录)
并且intersectionobserverentry也不返回对观察到的节点的引用
所以我们可以回退到检索部分以从中获取当前条目索引
const sections = document.querySelectorAll('section');
const colors = ['green','brown', 'blue'];
const action = function (entries) {
entries.forEach(entry => {
if(entry.isIntersecting) {
// retrieve the entry's index from sections
const i = [...sections].indexOf(entry.target)
// or... traverse to its parent praying for all the observed entries to be there
// console.log(entry.target.parentNode.querySelectorAll('section'))
entry.target.style.backgroundColor= colors[i]; //changing to background color to the color from colors array
} else {
return false; // going back to original background color???
}
});
}
const options = {
root: null,
rootMargin: "30% 0px",
threshold: 1
};
const observer = new IntersectionObserver(action, options);
sections.forEach(section => {
observer.observe(section);
});
header { height: 100vh; background: #ccc;}
.block {
position: relative;
width: 100%;
height: 30vh;
transition: .5s;
}
.block1 {background: #666;}
.block2 { background: #aaa;}
.block3 { background: #333;}
<header>header</header>
<section class="block block1">green</section>
<section class="block block2">brown</section>
<section class="block block3">blue</section>
TA贡献1804条经验 获得超8个赞
实现它的一种方法是使用 CSS 类。所以,当元素相交时,添加一个intersecting类,当它不相交时,删除它。并具有匹配块的相应 CSS。我不太确定 IntersectionObserver 选项,但我已经更改了它们以让您了解这种方法的工作原理。
const sections = document.querySelectorAll('section');
const action = function(entries) {
entries.forEach(entry => {
const elem = entry.target;
if (entry.isIntersecting) {
if (!elem.classList.contains("intersect")) {
elem.classList.add("intersect");
}
} else {
elem.classList.remove("intersect");
}
});
}
const options = {
// root: null,
// rootMargin: "30% 0px",
threshold: 0.5
};
const observer = new IntersectionObserver(action, options);
sections.forEach(section => {
observer.observe(section);
});
header {
height: 100vh;
background: #ccc;
}
.block {
position: relative;
width: 100%;
height: 100vh;
transition: .5s;
}
.block1 {
background: #666;
}
.block1.intersect {
background: green;
}
.block2 {
background: #aaa;
}
.block2.intersect {
background: brown;
}
.block3 {
background: #333;
}
.block3.intersect {
background: blue;
}
<header>header</header>
<section class="block block1">green</section>
<section class="block block2">brown</section>
<section class="block block3">blue</section>
添加回答
举报