我尝试使用scroll-snap
CSS属性来实现滚动/快照效果,表示效果良好。
但是当滚动/快照发生时,我需要触发一个事件。请问如何实现?
我尝试使用scroll-snap
CSS属性来实现滚动/快照效果,表示效果良好。
但是当滚动/快照发生时,我需要触发一个事件。请问如何实现?
Intersection Observer API
似乎(有点)有效。(在最新版的Firefox上似乎有问题——往上滚动时,观察器会失控并仅记录第一个部分——在最新版的Chrome上工作正常)
const observer = new IntersectionObserver(entries => {
entries.forEach(elem => {
if (elem.isIntersecting) {
const text = elem.target.querySelector('h2').innerText;
console.log('Ping! Visible: ', text);
}
});
});
document.querySelectorAll('section').forEach(elem => observer.observe(elem));
.scroller {
height: 300px;
overflow-y: scroll;
scroll-snap-type: y mandatory;
}
.scroller section {
height: 300px;
background: gray;
border: 1px solid black;
scroll-snap-align: start;
}
<article class="scroller">
<section>
<h2>Section one</h2>
</section>
<section>
<h2>Section two</h2>
</section>
<section>
<h2>Section three</h2>
</section>
</article>
我不知道是否有其他方法。