gpt4 book ai didi

javascript - 我怎样才能 "snap scroll"并在捕捉时触发事件?

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:21 30 4
gpt4 key购买 nike

我尝试使用 scroll-snap CSS 属性,它在表示方面效果很好。

但我需要在滚动/捕捉时触发一个事件。我怎样才能做到这一点?

最佳答案

正如 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>

不知道有没有别的办法。

关于javascript - 我怎样才能 "snap scroll"并在捕捉时触发事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326493/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com