我想实现滚动事件功能,将我转发到页面上的某个位置,就像在FullPage.js中一样。 示例:https://alvarotrigo.com/fullPage 我尝试添加onscroll事件监听器,它区分滚动方向,然后执行scrollTo(),但这似乎是一个坏主意。我该如何正确实现?提前致谢。 到目前为止我尝试了什么:
function throttle(fn, delay) {
let last;
let timer;
return () => {
const now = +new Date;
if (last && now < last + delay) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn();
}, delay);
} else {
last = now;
fn();
}
};
}
var scrollPos = 0;
function smooth_scroll(){
// detects new state and compares it with the new one
if ((document.body.getBoundingClientRect()).top > scrollPos)
{
window.scrollTo({ top: 0, behavior: 'smooth' })
}
else
{
window.scrollTo({ top: 1000, behavior: 'smooth' })//as an example
}
// saves the new position for iteration.
scrollPos = (document.body.getBoundingClientRect()).top;
}
window.addEventListener('scroll', throttle(smooth_scroll, 1000));
我希望它能像这样工作:无论何时我向下滚动它都会将我转到底部(1000,0),当我向上滚动时它会让我到达顶部。一切顺利。
如果查看示例网站,您可以看到它们没有滚动列表。他们正在为一个包装器和它的孩子们制作动画:
class:fullpage-wrapper
attribute they change: transform:translate3d(0px, -937px, 0px);
会发生什么事情,所有元素都在一个包装内,然后向上移动到盒子的高度。此页面的平滑效果由特定的缓动提供,可以附加到CSS动画。
因此,如果您想获得相同的“滚动”效果,您需要考虑动画解决方案。因此,您可以坚持使用空白的CSS-Animations或Framework / Library特定的。