我正在尝试使用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>
您的滚动事件不断触发并覆盖您的scrollIntoView
。为了阻止这种情况,您可以设置容器的overflow
属性,使其不再允许滚动,禁用事件,然后在调用scrollIntoView
之前使用计时器重新启用它。
entries.forEach(entry => { if (entry.isIntersecting == true) { console.log(entry.target.offsetTop); document.body.setAttribute('style','overflow:hidden;'); setTimeout(function(){ document.body.setAttribute('style','overflow:visible;'); entry.target.scrollIntoView(true); }, 250); }
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title></title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body,
html {
position: absolute;
-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);
document.body.setAttribute('style','overflow:hidden;');
setTimeout(function(){
document.body.setAttribute('style','overflow:visible;');
entry.target.scrollIntoView(true);
}, 250);
}
});
},
{threshold: 0.10},
);
pages.forEach(page => {
observer.observe(page);
});
</script>
</body>
</html>
[Note