【发布时间】:2020-03-05 22:44:25
【问题描述】:
我正在尝试使用intersectionObserver 制作幻灯片网站。基本上,我 grep 元素并监听相交事件,然后我想将 window.srollTo 设置为元素的 offsetTop。我试过window.scrollTo(0, 10)、elem.scrollIntoView()、window.scrollBy(),但没有任何效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title></title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body,
html {
position: ablolute;
-ms-overflow-style: none;
display: block;
height: 100vh;
width: 100%;
}
body::-webkit-scrollbar {
width: 0 !important;
}
.page {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="page">one</div>
<div class="page">two</div>
<div class="page">three</div>
<div class="page">four</div>
<script>
const pages = document.querySelectorAll('.page');
const observer = new IntersectionObserver(
entries => {
entries.forEach(entry => {
if (entry.isIntersecting == true) {
console.log(entry.target.offsetTop);
entry.target.scrollIntoView(top);
}
});
},
{threshold: 0.01},
);
pages.forEach(page => {
observer.observe(page);
});
</script>
</body>
</html>
【问题讨论】:
-
entry.target.scrollIntoView(top);top从何而来? -
嗨,Maksym,请您编辑帖子的标题。不清楚您的问题是什么。
标签: javascript ecmascript-5 intersection-observer