移动端JS屏幕触摸事件Touch
随着移动互联的到来, 人们使用移动设备浏览网页的频率高了,我们平时在pc浏览器上用的事件,比如:click, mouseover等, 已经无法满足移动设备触摸屏的特点。
touch是移动端的触摸事件 而且是一组事件。
加粗样式 如何使用touch,
1.绑定事件:element.addEventListener(‘touchstart’,function () { });
2.事件对象:
TouchList------触摸点(一个手指触摸就是一个触发点,和屏幕的接触点的个数)的集合
changedTouches 改变后的触摸点集合
targetTouches 当前元素的触发点集合
touches 页面上所有触发点集合
3.触摸点集合在每个事件触发的时候会不会去记录触摸
changedTouches 每个事件都会记录
targetTouches,touches 在离开屏幕的时候无法记录触摸点
4.分析滑动实现的原理:
4.1 就是让触摸的元素随着手指的滑动做位置的改变
4.2 位置的改变:需要当前手指的坐标
4.3 在每一个触摸点中会记录当前触摸点的坐标 e.touches[0] 第一个触摸点
4.4 clientX clientY 基于浏览器窗口(视口)
4.4 pageX pageY 基于页面(视口)
4.4 screenX screenY 基于屏幕
事件类型:
touchstart : 触摸开始(手指放在触摸屏上)
touchmove : 拖动(手指在触摸屏上移动)
touchend : 触摸结束(手指从触摸屏上移开)
touchenter :移动的手指进入一个dom元素。
touchleave :移动的手指离开一个dom元素。
还有一个touchcancel,是在拖动中断时候触发。
代码:
window.onload = function () {
var box = document.querySelector('.box');
box.addEventListener('touchstart', function (e) {
console.log('start');
console.log(e);
})
box.addEventListener('touchmove', function (e) {
console.log('move');
console.log(e);
})
box.addEventListener('touchend', function (e) {
console.log('end');
console.log(e);
})
box.onclick = function (e) {
console.log(e);
console.log('click');
}
}
手写 移动端手指 滑动事件
//手指滑动距离必须超过50px
var bandSlide = function (dom, leftCallBack, rightCallback) {
var startX = 0;
var distanse = 0;
var ismove = false;
dom.addEventListener('touchstart', function (e) {
startX = e.touches[0].clientX;
})
dom.addEventListener('touchmove', function (e) {
distanse = e.touches[0].clientX - startX;
ismove = true
})
dom.addEventListener('touchend', function (e) {
if (ismove && Math.abs(distanse) > 50) {
if (distanse > 0) {
rightCallback && rightCallback(this, e);
} else {
leftCallBack && leftCallBack(this, e);
}
}
})
}
bandSlide(document.querySelector(".box"), function (e) {
console.log("zuo");
}, function (e) {
console.log("you");
})
}
手写原生点击tap事件
window.onload = function () {
//手指滑动距离必须超过50px
var bandSlide = function (dom, callBack) {
var startTime = 0;
var ismove = false;
dom.addEventListener('touchstart', function (e) {
startTime = Date.now();
})
dom.addEventListener('touchmove', function (e) {
ismove = true
})
dom.addEventListener('touchend', function (e) {
if (!ismove && (Date.now() - startTime) < 150) {
callBack && callBack(e);
}
startTime =0;
ismove =false;
})
}
bandSlide(document.querySelector(".box"), function (e) {
console.log("点击");
console.log(e);
})
}