主要运用原理:JS 滚动监听事件、JS 移动端touch监听事件、函数节流、DOM操作
实现
<div class="page-container">
<div class="page-item">1</div>
<div class="page-item">2</div>
<div class="page-item">3</div>
</div>
html,
body {
padding: 0;
margin: 0;
overflow: hidden;
}
.page-container {
position: relative;
top: 0;
transition: all 1000ms ease;
touch-action: none;
}
.page-item {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
border: 1px solid #ddd;
}
var container = document.querySelector('.page-container')
// 获取根元素高度, 页面可视高度
var viewHeight = document.documentElement.clientHeight
// 获取滚动的页数
var pageNum = document.querySelectorAll('.page-item').length
// 初始化当前位置, 距离原始顶部距离
var currentPosition = 0
// 设置页面高度
container.style.height = viewHeight + 'px'
// 向下滚动页面
function goDown () {
if (currentPosition > - viewHeight * (pageNum - 1)) {
currentPosition = currentPosition - viewHeight
container.style.top = currentPosition + 'px'
}
}
//初始化滚动事件
// 向上滚动页面
function goUp () {
if (currentPosition < 0) {
currentPosition = currentPosition + viewHeight
container.style.top = currentPosition + 'px'
}
}
//节流函数:即在规定时间内只会触发一次指定方法, 用于滚动时防止多次触发
function throttle (fn, delay) {
let baseTime = 0
return function () {
const currentTime = Date.now()
if (baseTime + delay < currentTime) {
fn.apply(this, arguments)
baseTime = currentTime
}
}
}
//监听鼠标滚动
var handlerWheel = throttle(scrollMove, 1000)
// firefox的页面滚动事件其他浏览器不一样
if (navigator.userAgent.toLowerCase().indexOf('firefox') === -1) {
document.addEventListener('mousewheel', handlerWheel)
} else {
document.addEventListener('DOMMouseScroll', handlerWheel)
}
function scrollMove (e) {
if (e.deltaY > 0) {
goDown()
} else {
goUp()
}
}
//监听移动端touch操作
var touchStartY = 0
document.addEventListener('touchstart', event => {
touchStartY = event.touches[0].pageY
})
var handleTouchEnd = throttle(touchEnd, 500)
document.addEventListener('touchend', handleTouchEnd)
function touchEnd (e) {
var touchEndY = e.changedTouches[0].pageY
if (touchEndY - touchStartY < 0) { // 向上滑动, 页面向下滚动
goDown()
} else {
goUp()
}
}
原文:https://www.cnblogs.com/EricZLin/p/12310254.html