这个博客更新了一下下面的js代码https://blog.csdn.net/qq_47658204/article/details/108791392
项目场景:
准备移动端实现滑动翻页效果
首先你得了解这三个函数 touchstart touchmove touchend及其相关的用法
页面你的自己搭建,我就不做实例了。我这里一共有四个页面。
大致结构
<meta name="viewport" content="width=device-width, initial-scale=1.0,shrink-to-fit=no">//不要忘了加
#wrapper 宽高100% overflow-hiden
#content 宽高100%
.page1 宽高100% 包含有其他的页面点击事件
.page2 宽高100% 包含有其他的页面点击事件
.page3 宽高100% 包含有其他的页面点击事件
.page4 宽高100% 包含有其他的页面点击事件
如果你的页面没有其他的,会干扰屏幕滑动的,其他的页面事件,你可以去参考其他的人的更加便捷的方法,
我这里主要是不让页面事件影响滑动操作
-接下来就是js代码了
<script type="text/javascript">
var wrapper = document.getElementById('wrapper'),//整体
content = document.getElementById('content');//滑动容器
var scrollHeight = content.scrollHeight //所有页面的总体高度
//建议去了解一下 scrollHeight offsetHeigth offsetTop ....
var itemHeight = wrapper.offsetHeight; //可见区域高度
var index = 3; //滑动计数
var hheight = 0; //翻 页 数量
var moveY, //滑动距离
endY, //滑动停止的Y坐标
startY; //滑动开始的Y坐标
// 触摸开始
function boxTouchStart(e) {
e.preventDefault(); //防止其他事件影响操作
var touch = e.touches[0];//阿巴阿巴
startY = touch.pageY;//记录开始滑动位置
}
// 触摸移动
function boxTouchMove(e) {
e.preventDefault();
var touch = e.touches[0];
moveY = touch.pageY - startY;//计算滑动的距离,后面方便判断往那个方向滑动
}
// 触摸结束
function boxTouchEnd(e) {
e.preventDefault();
//向下滑动,返回上一页
//滑动初始位置 - 结束位置 > 0
if(moveY > 0) {
if(index >= 3) {
console.log("已经是第一页了");
index=3;
return false;
}
index++;//页面还没切换前加一,向上滑动会减少index,这里需要加回来
hheight = scrollHeight-((index+1)*itemHeight);//计算页面移动偏移量
content.style.webkitTransform = 'translateY(-'+(hheight)+'px)';
}
//向上滑动 ,滑动到下一页
else if(moveY < 0) {
if(index <= 0) {
console.log("不能再滑动了");
index=0;
return false;
}
hheight = scrollHeight-(index*itemHeight);//
content.style.webkitTransform = 'translateY(-'+(hheight)+'px)';
index--;//切换后减一
}
moveY=0;//防止点击触发
}
//给content绑定事件
content.addEventListener('touchstart', boxTouchStart, false )
content.addEventListener('touchmove', boxTouchMove, false)
content.addEventListener('touchend', boxTouchEnd, false)
</script>
you shi diao tou fa de yi tian