我尝试使用scroll-snap CSS属性,它在表示方面工作得很好。
但我需要在滚动/捕捉时触发一个事件。我该怎么做呢?
发布于 2019-08-02 21:35:16
正如Mladen建议的那样,使用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>
我不知道还有没有别的办法。
https://stackoverflow.com/questions/57326493
复制相似问题