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>
添加回答
舉報