之前想实现全屏滚动,基本都要依靠 js 来实现,不是使用 fullpage.js 插件,就是自己手撸实现。原理都是使用 js 监听鼠标齿轮的滚动,手动控制页面的滚动。
if (navigator.userAgent.toLowerCase().indexOf('firefox') === -1) {
document.addEventListener('mousewheel', scrollPage)
} else {
document.addEventListener('DOMMouseScroll', scrollPage)
}
但若无需兼容 IE 浏览器,完全可以用简单的 css 来实现该功能,无需任何 js 做边界判断,滑动停止自动定位到想要的位置。直接上代码。
/* 在父容器上面使用 scroll-snap-type 属性 */
.container {
scroll-snap-type: y mandatory;
height: 100vh;
overflow: auto;
}
/* 在子元素上使用 scroll-snap-align 属性 */
.item {
scroll-snap-align: start;
height: 100%;
position: relative;
}
css 实现的不足:
但 css 实现,除了兼容性还有个不足,无法监听事件,也就是每次滚动定位结束后,我们想执行某个回调是没办法的。这种情况下还是要依赖 js。
解决方案:
使用 js 监听父容器的滚动事件,遍历所有子元素,若某个子元素的上边缘与父容器的上边缘一致或者小于 10(加点容错区间),则该子元素就是当前定位的元素。
var timer = null;
// 滚动事件开始
container.addEventListener('scroll', function () {
clearTimeout(timer);
timer = setTimeout(function () {
// 无滚动事件触发,则认为停止滚动了
[].slice.call(container.children).forEach(function (eleList, index) {
if (Math.abs(eleList.getBoundingClientRect().top - container.getBoundingClientRect().top) < 10) {
// 回调
// index 为当前定位的元素的索引
}
});
}, 100);
});