Mis*_*hko 5 javascript scroll intersection-observer
在元素上设置相交观察器。当元素滚动经过某个点时,会按预期触发交集观察器处理程序。但是,如果单击按钮将元素滚动经过同一点,则不会触发处理程序。
这是为什么?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
});
})Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
<div id="container">
<div class="inner-container">
<button id="button">Scroll</button>
</div>
<div id="hello">Hello</div>
</div>Run Code Online (Sandbox Code Playgroud)
n1k*_*oza -1
从选项对象中删除rootMargin ,它将相交,您也可以决定可见性的百分比,如果即使 50% 可见,也应该触发回调,您可以提供内部选项对象
{ threshold: 0.5}
Run Code Online (Sandbox Code Playgroud)
所以所有...