如何在每个滚动事件上实现自动滚动到下一节网页,但不排除带有香草JavaScript的滚动条。
我尝试使用jQuery动画功能、滚动功能和fullpage.js库,但没有成功。
发布于 2022-04-13 11:42:42
您可以使用scroll()或scrollIntoView()方法来获取您要查找的内容。前者基于从页面顶部偏移的像素滚动,而后者则滚动到给定的元素。
来自MDN:
Window.scroll()方法将窗口滚动到文档中的特定位置。元素接口的scrollIntoView()方法滚动元素的父容器,这样调用scrollIntoView()的元素对用户是可见的。
为了顺利滚动,您可以在这两种方法中使用smooth行为,如下所示:
// Smoothly scrolls to 200 pixels from the top
window.scroll({top: 200, behavior: 'smooth'});和
var el = document.getElementById('fooBar');
// Smoothly scrolls to the top of the element provided
el.scrollIntoView({behavior: 'smooth'});当然,如果要基于鼠标轮事件执行此操作,则需要为此设置一个侦听器(可能是wheel或scroll事件)。
发布于 2022-04-13 13:50:19
好吧我的项目也有同样的问题。我试着用_.throttle或_.debounce函数来实现它,并且遇到了描述的相同功能。我认为,如果我们知道如何完全防止滚动出节气门功能,它将工作。但我不知道该怎么做。这是我的版本
代码:
let screens = ["#id1", "#id2", "#id3", "#id4",
"#id5", "#id6", "#id7"];
let numberOfScreen = 0;
let isScrolling = false;
let lastScrollTop = 0;
document.body.addEventListener("scroll", _.throttle(()=>{
var st = window.pageYOffset || document.body.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
let i = numberOfScreen;
if (st > lastScrollTop){
i++;
if(i >= screens.length){
i = screens.length-1;
}
} else {
i--;
if(i<0){
i = 0;
}
}
window.location = screens[i];
setTimeout(()=>{
numberOfScreen = i;
},1000)
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, 1000, { 'trailing': false}));`
https://stackoverflow.com/questions/71856353
复制相似问题