当某个元素在视图中显示一定数量(0-100%)时,就会触发IntersectionObserver。这意味着,当元素为时,它不再触发视口中的100%,因为阈值没有变化。
我有一个高度为200vh的元素,当我在IntersectionObserver元素上滚动时,希望触发它。因此,元素总是100%在视口内。
有什么方法可以在滚动元素时触发观察者吗?
我不能使用滚动事件,因为我使用的是CSS scroll-snap,它导致事件被浏览器吞没,然后JS才能检测到它。
发布于 2022-04-09 06:14:34
希望我能够在这里理解您的挑战,所以我将尝试提出一个适合您的用例的解决方案,即使没有代码可用作参考。
据我所知,您正在使用scroll-snap在用户通过滚动进行交互时抓取部分,您的意图是让交叉观察者在用户从一个部分移动到另一个部分时触发。
在下面的示例中,您将看到节是如何被抓取的,但是调试器显示了显示给用户的部分。
const debuggerSpan = document.querySelector('#current-section');
const sections = [...document.querySelectorAll('.scroll-snap-item')];
const div = document.querySelector('.scroll-snap-container');
/*
* This method will get called any time a section touches the top
* of the viewport.
*/
const intersectionDetected = (entries, observer) => {
entries.forEach((entry) => {
const {
innerText
} = entry.target;
if (!entry.isIntersecting) return;
// Making it obvious that the current section is correct.
debuggerSpan.innerText = innerText;
});
};
const observer = new IntersectionObserver(intersectionDetected, {
/*
* Root should be div and not the default (doc).
*/
root: div,
/*
* Negative margin from the bottom creates an invisible line
* to detect intersections.
*
* The reason why the recommendation is to use -1% and -99% is to
* avoid the race condition between two intersections happening
* (AKA the section about to be out of the viewport and the section
* about to enter the viewport).
*/
rootMargin: '-1% 0% -99% 0%',
/*
* Default value but making it explicit as this is the
* only configuration that works.
*/
threshold: 0
});
sections.forEach(section => observer.observe(section));.scroll-snap-item {
height: 100vh;
display: grid;
place-items: center;
font-size: 4rem;
scroll-snap-align: start;
}
.scroll-snap-container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
height: 100vh;
}
/* Decorative stuff below*/
.scroll-snap-item:nth-child(odd) {
background-color: gray;
}
aside {
position: fixed;
font-size: 1.6rem;
bottom: 16px;
right: 16px;
background-color: #333;
color: white;
padding: 16px;
border-radius: 32px;
}<div class="scroll-snap-container">
<section class="scroll-snap-item">1</section>
<section class="scroll-snap-item">2</section>
<section class="scroll-snap-item">3</section>
<section class="scroll-snap-item">4</section>
<section class="scroll-snap-item">5</section>
<section class="scroll-snap-item">6</section>
</div>
<aside>Current section: <span id="current-section"></span></aside>
我写了几篇实用的文章,介绍了这一切背后的原因,以及解决这一问题的思考过程。如果事情不够清楚,请随意阅读,并留下评论:
这两种方法都是快速读取的,应该提供解决这个问题所需的一切,以及更复杂的交叉口观察者问题。另外,可以随意使用我编写的这个叫做十字路口观赏者游乐场的工具,在这里您可以尝试不同的配置,看看它们是如何影响交叉触发器的。
希望这能帮上忙!
https://stackoverflow.com/questions/57946043
复制相似问题