废话不多讲,直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style></style>
</head>
<body>
<div class="box">
<div class="page">第一頁
<div class="next">1</div></div>
<div class="page">第二頁
<div class="next">2</div></div>
<div class="page">第三頁
<div class="next">3</div></div>
<div class="page">第四頁
<div class="next">4</div></div>
<div class="page">第五頁
<div class="next">5</div></div>
</div>
<script>
var pageEl = document.getElementsByClassName("page"); //节点集合
var nextEl = document.getElementsByClassName("next"); //节点集合
var startY, endY, speed = 0;//开始触碰点,结束触碰点,滑动距离
var curPage = 0;//当前页
document.addEventListener("touchstart",
function(e) {
startY = e.touches[0].pageY;
}) document.addEventListener("touchmove",
function(e) {
endY = e.touches[0].pageY;
speed = startY - endY;
e.preventDefault();
},
{
passive: false
}) document.addEventListener("touchend",
function(e) {
if (Math.abs(speed) > 150) { //滑动达到一定大小才滑动
if (speed > 0) { //正负,判断是向上或向下
pageNext(curPage) qingling()
} else {
pageDown(curPage) qingling()
}
}
})
//点击翻页
for (var i = 0; i < nextEl.length; i++) {
nextEl[i].onclick = function() {
pageNext(curPage)
}
}
//向下翻页
function pageNext(n) {
// console.log(n)
if (n < pageEl.length - 1) {
n++;
curPage++;
setTimeout(function() {
pageEl[n - 1].classList.add('hide')
},
1000);
pageEl[n - 1].classList.add('out-top') pageEl[n - 1].classList.remove('in-top', 'out-down', 'in-down') pageEl[n].classList.add('in-top') pageEl[n].classList.remove('out-top', 'out-down', 'in-down') pageEl[n].style.display = 'block';
if (n = pageEl.length - 1) {
//当最后一个页面时隐藏向下按钮
nextEl[4].style.display = "none"
}
}
}
//向上翻页
function pageDown(n) {
if (n > 0) {
n--;
curPage--;
setTimeout(function() {
pageEl[n + 1].classList.add('hide')
},
1000);
console.log(pageEl[n + 1]) pageEl[n + 1].classList.add('out-down') pageEl[n + 1].classList.remove('out-top', 'in-top', 'in-down') pageEl[n].classList.add('in-down') pageEl[n].classList.remove('out-top', 'out-down', 'in-top') if (n < pageEl.length - 1) { //当不是最后一个页面时显示向下按鈕
nextEl[4].style.display = "block"
}
}
}
// 数据清零
function qingling() {
startY = 0;
endY = 0;
speed = 0;
}
</script>
</body>
</html>