概述
-
移动端浏览器触摸事件:
-
每个触摸事件都包括了三个触摸列表,每个列表里包含了对应的一系列触摸点(用来实现多点触控)
-
1.touches: 当前位于屏幕上所有手指列表
-
2.targetTouches: 位于当前DOM元素上手指的的列表
-
3.changedTouches: 涉及当前事件手指的列表
每个touch对象包含属性如下:
clientX:触摸目标在视口中的x坐标。
clientY:触摸目标在视口中的y坐标。
identifier:标识触摸的唯一ID。
pageX:触摸目标在页面中的x坐标。
pageY:触摸目标在页面中的y坐标。
screenX:触摸目标在屏幕中的x坐标。
screenY:触摸目标在屏幕中的y坐标。
target:触摸的DOM节点目标。
demo实例(在vue中的实例实现自定义横滚动条)
<template>
<!--进度条-->
<div class="hot-nav-bottom">
<div class="hot-nav-bottom-inner" :style="innerBarStyle"></div>
</div>
</template>
<script>
export default {
data(){
return {
// 1. 屏幕的宽度
screenW: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
// 2. 滚动内容的宽度
scrollContentW: 720,
// 3. 滚动条背景的长度
bgBarW: 100,
// 4. 滚动条的长度
barXWidth: 0,
// 5. 起点
startX: 0,
// 6. 记录结束点
endFlag: 0,
// 7. 移动的距离
barMoveWidth: 0
}
},
computed:{
innerBarStyle(){
return {
width: `${this.barXWidth}px`,
left: `${this.barMoveWidth}px`
}
}
},
mounted() {
this.getBottomBarWidth();
this.bindEvent();
},
methods:{
// 获取滚动条的长度
getBottomBarWidth(){
this.barXWidth = this.bgBarW * (this.screenW / this.scrollContentW)
},
// 移动端事件监听
bindEvent(){
this.$el.addEventListener('touchstart',this.handleTouchStart,false);
this.$el.addEventListener('touchmove',this.handleTouchMove,false);
this.$el.addEventListener('touchend',this.handleTouchEnd,false);
},
// 开始触摸
handleTouchStart(event){
// console.log(event.touches);
// 1. 获取第一个触点
let touch = event.touches[0];
// 2.求出起始点
this.startX = Number(touch.pageX);
// console.log(this.startX);
},
// 开始移动
handleTouchMove(){
// console.log('开始移动');
// 1. 获取第一个触点
let touch = event.touches[0];
// 2. 求出移动的距离
let moveWidth = Number(touch.pageX) - this.startX;
// console.log(moveWidth);
// 3. 求出滚动条走的距离
this.barMoveWidth = -((this.bgBarW / this.scrollContentW) * moveWidth - this.endFlag);
// 4. 边界值处理
if(this.barMoveWidth <= 0){ // 左边
this.barMoveWidth = 0;
}else if(this.barMoveWidth >= this.bgBarW - this.barXWidth){ // 右边
this.barMoveWidth = this.bgBarW - this.barXWidth;
}
},
// 结束触摸
handleTouchEnd(){
//console.log('结束触摸');
this.endFlag = this.barMoveWidth;
},
}
}
</script>