Javascript 尝试使用intersectionObserver将窗口滚动到元素位置时出现问题
我正在尝试使用intersectionObserver制作幻灯片放映网站。基本上,我grep元素并监听交叉点事件,然后我想将window.srollTo设置为元素的offsetTop。我已经尝试了window.scrollTo(0,10)、elem.scrollIntoView()、window.scrollBy(),但没有任何效果Javascript 尝试使用intersectionObserver将窗口滚动到元素位置时出现问题,javascript,ecmascript-5,intersection-observer,Javascript,Ecmascript 5,Intersection Observer,我正在尝试使用intersectionObserver制作幻灯片放映网站。基本上,我grep元素并监听交叉点事件,然后我想将window.srollTo设置为元素的offsetTop。我已经尝试了window.scrollTo(0,10)、elem.scrollIntoView()、window.scrollBy(),但没有任何效果 <!DOCTYPE html> <html lang="en"> <head> <meta charset="
<!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>
* {
保证金:0;
填充:0;
框大小:边框框;
}
身体,
html{
位置:绝对;
-ms溢出样式:无;
显示:块;
高度:100vh;
宽度:100%;
}
正文::-webkit滚动条{
宽度:0!重要;
}
.第页{
宽度:100%;
身高:100%;
}
一
二
三
四
const pages=document.queryselectoral('.page');
const observer=新的IntersectionObserver(
条目=>{
entries.forEach(entry=>{
if(entry.isIntersecting==true){
console.log(entry.target.offsetTop);
entry.target.scrollIntoView(顶部);
}
});
},
{阈值:0.01},
);
pages.forEach(第=>{
观察者观察(第页);
});
首先滚动视图
采用布尔值
或选项对象
。我不知道top应该是什么,因为它不在您的代码中,但它不正确
您的scroll事件不断触发并覆盖您的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);
}
例如:
* {
保证金:0;
填充:0;
框大小:边框框;
}
身体,
html{
位置:绝对位置;
-ms溢出样式:无;
显示:块;
高度:100vh;
宽度:100%;
}
正文::-webkit滚动条{
宽度:0!重要;
}
.第页{
宽度:100%;
身高:100%;
}
一
二
三
四
const pages=document.queryselectoral('.page');
const observer=新的IntersectionObserver(
条目=>{
entries.forEach(entry=>{
if(entry.isIntersecting==true){
console.log(entry.target.offsetTop);
document.body.setAttribute('style','overflow:hidden;');
setTimeout(函数(){
document.body.setAttribute('style','overflow:visible;');
entry.target.scrollIntoView(true);
}, 250);
}
});
},
{阈值:0.10},
);
pages.forEach(第=>{
观察者观察(第页);
});
entry.target.scrollIntoView(顶部)
top来自哪里?你好,Maksym,请编辑你的文章标题。你的问题是什么还不清楚。