繁体   English   中英

为什么在使用 scrollTo 或 scrollIntoView 时不会触发交叉点观察者处理程序?

[英]Why intersection observer handler is not fired when using scrollTo or scrollIntoView?

在元素上设置了一个相交观察器。 当元素滚动超过某个点时,交集观察者处理程序将按预期触发。 但是,如果单击按钮将元素滚动到同一点之后,则不会触发处理程序。

这是为什么? 有没有办法在使用scrollTo / scrollIntoView时强制触发处理程序?

 const container = document.getElementById("container"); const hello = document.getElementById("hello"); const button = document.getElementById("button"); const options = { rootMargin: "-100px 0px 0px 0px", threshold: 1 } const handleIntersect = entries => { entries.forEach((entry) => { console.log("handleIntersect") }); }; const observer = new IntersectionObserver(handleIntersect, options); observer.observe(hello); button.addEventListener("click", () => { container.scrollTo({ top: 120 }); })
 body { margin: 0; } #container { background-color: #ddd; height: 400px; overflow-y: auto; }.inner-container { height: 100px; border-bottom: 1px solid #bbb; position: absolute; top: 0; left: 0; right: 0; text-align: right; } #button { margin: 40px; font-size: 20px; } #hello { display: inline-block; padding: 20px 40px; background-color: blue; color: white; margin-top: 150px; margin-bottom: 500px; }
 <div id="container"> <div class="inner-container"> <button id="button">Scroll</button> </div> <div id="hello">Hello</div> </div>

你应该添加 isIntersecting 检查

if(entry.isIntersecting){
console.log("hello")
}

我不知道这是否可以解决您的问题,但是我认为当我们将 scrollIntoView 链接到按钮时,如果单击该按钮,我们会为滚动条的 position 指定一个值,例如当我们单击具有 scrollTo 的按钮时() function 我们希望滚动条位于特定位置,但这并不意味着滚动条滑动到与滚动鼠标时发生的动作相似的位置。

换句话说,交叉点 API 会在您越过特定 position 或某个点时触发,但是即使您只是跳过该点并直接跳到所需的 Z4757FE07FD492A8BE0EA6A760D683D6E 时,它也不会触发

如果您想知道,当您使用 scrollTo() 平滑滚动网页时,您可以直观地看到滚动条滑到特定点,就好像它通过了阈值点,但事实并非如此,在幕后滚动条只是跳过所有内容并直接移动指定的position。

解决问题的一种方法(效率不高)是使用循环,尝试从当前页面偏移值循环到目标值,而不是将值硬编码到 scrollIntoView(),它确实为您提供了所需的 output 但滚动 animation 将贫穷,它失去了它的目标。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM