如何知道滚动到元素是用Javascript完成的

如何知道滚动到元素是用Javascript完成的

本文介绍了如何知道滚动到元素是用Javascript完成的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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完成的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 12:06