问题描述
我正在使用Javascript方法Element.scrollIntoView()
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView
I am using Javascript method Element.scrollIntoView()
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
有什么方法可以让我知道滚动结束的时间.假设有动画,或者我设置了{behavior: smooth}
.
Is there any way I can get to know when the scroll is over. Say there was an animation, or I have set {behavior: smooth}
.
我假设滚动是异步的,并且想知道是否有任何类似回调的机制.
I am assuming scrolling is async and want to know if there is any callback like mechanism to it.
推荐答案
您可以使用 IntersectionObserver
,检查元素 <IntersectionObserver
回调函数中的c3>
You can use IntersectionObserver
, check if element .isIntersecting
at IntersectionObserver
callback function
const element = document.getElementById("box");
const intersectionObserver = new IntersectionObserver((entries) => {
let [entry] = entries;
if (entry.isIntersecting) {
setTimeout(() => alert(`${entry.target.id} is visible`), 100)
}
});
// start observing
intersectionObserver.observe(box);
element.scrollIntoView({behavior: "smooth"});
body {
height: calc(100vh * 2);
}
#box {
position: relative;
top:500px;
}
<div id="box">
box
</div>
这篇关于如何知道滚动到元素是用Javascript完成的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!