【问题标题】:single intersection observer for multiple entries多个条目的单个交叉点观察器
【发布时间】:2021-02-23 15:29:33
【问题描述】:
无法完全理解 IntersectionObserver
在下面的示例中,一切正常,但我试图只为多个条目编写一个观察者
我收到了各种错误消息。
请帮忙
let io = new IntersectionObserver((entries)=>{
entries.forEach(entry=>{
if(entry.isIntersecting){navt.classList.remove('navt1');}
else{navt.classList.add('navt1');}
})
})
let io2 = new IntersectionObserver((entries)=>{
entries.forEach(entry=>{
if(entry.isIntersecting){gotopw.style.display = 'block';}
else{gotopw.style.display = 'none';}
})
})
$(document).ready(function(){
io.observe(document.querySelector('#wrapt'));
io2.observe(document.querySelector('#apanel'));
});
【问题讨论】:
标签:
javascript
intersection-observer
【解决方案1】:
每个相交的实体指的是相交的元素。因此,要创建单个 IntersectionObserver,您只需利用它即可。
这是一个显示概念的简化示例。请注意,有两个“框”可以滚动到视图中。当他们滚动查看时,背景颜色会单独更改。我使用了交叉比率,以便您可以看到发生的变化。
modify() 和 revert() 函数表示您将在两个交集阈值之一中执行的操作。
元素 id 的测试是允许对多个元素使用一个 IntersectionObserver 的技巧。
慢慢滚动以查看这两个框。
let io = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
modify(entry.target);
} else {
revert(entry.target);
}
})
}, {
threshold: 0.5
})
function modify(el) {
if (el.id === "wrapt") {
el.style.backgroundColor = 'red';
}
if (el.id === "apanel") {
el.style.backgroundColor = 'green';
}
}
function revert(el) {
if (el.id === "wrapt") {
el.style.backgroundColor = 'initial';
}
if (el.id === "apanel") {
el.style.backgroundColor = 'initial';
}
}
io.observe(document.querySelector('#wrapt'));
io.observe(document.querySelector('#apanel'));
#wrapt {
border: 2px solid black;
height: 100px;
width: 100px;
}
#apanel {
border: 2px solid blue;
height: 100px;
width: 100px;
}
.empty {
height: 400px;
width: 100px;
}
<div class="empty"> </div>
<div id="wrapt">Wrapt</div>
<div class="empty"></div>
<div id="apanel">aPanel</div>