ios下有多指触屏事件,如
gesturestart: 当手指触摸屏幕,并且有两根以上手指执行;
gesturechange:当有两根或多根手指在屏幕上,并且有手指移动的时候触发;
gestureend:当多余两根手指头抬起时执行;
本事件下有我们常用的事件如多指缩放 e.scale 多指旋转e.rotation 等,这里我们处理缩放事件
但是此事件在安卓下并不兼容,显然这事件是不可行的,为了兼容安卓和iOS,我们需要自己去封装多指事件;
这里我只贴出部分代码解释,首先,封装一个setGesture方法,此方法就是完全替代iOS下的多指事件,
setGesture方法接收一个参数inti,此参数为一个对象,对象里有四个属性,分别为el、start、change和end,
el是必须有的,为传入的元素,如 document.getElementById(id);
start是可选的,和iOS下gesturestart的属性相同:实现当手指触摸屏幕,并且有两根以上手指执行;
change是可选的,和iOS下gesturechange的属性相同:实现当有两根或多根手指在屏幕上,并且有手指移动的时候触发;
end是可选的,和iOS下gestureend的属性相同:当多余两根手指头抬起时执行;
如
setGesture({
el: 元素,
start: function (e) {
//相应的逻辑...
},
change: function (e) {
//相应的逻辑...
},
end: function (e) {
//相应的逻辑...
}
})
/*
inti:{
el:element, //元素对象(必须)
start:fn,
change:fn,
end:fn,
}
*/
function setGesture(inti) {
var el = inti.el;
if (!el) return;
var scaleStart = 0;
var isGesture = false;
var startPoint = [];
//斜率 Math.atan2(y,x) 由一条直线与x轴正方向所成的角的正切 返回值的弧度
//角度转弧度 Math.PI/180
//弧度转角度 rad*180/Math.PI
el.addEventListener('touchstart', function (e) {
if (e.touches.length >= 2) {
isGesture = true;//记录进行了多指操作
startPoint[0] = { x: e.touches[0].pageX, y: e.touches[0].pageY };
startPoint[1] = { x: e.touches[1].pageX, y: e.touches[1].pageY };
inti.start && inti.start.call(el, e);//手指按下时执行
}
});
el.addEventListener('touchmove', function (e) {
if (e.touches.length >= 2 && isGesture) {
var nowPoint = []; //移动时手指的坐标点
nowPoint[0] = { x: e.touches[0].pageX, y: e.touches[0].pageY };
nowPoint[1] = { x: e.touches[1].pageX, y: e.touches[1].pageY };
var startDis = getDis(startPoint[1], startPoint[0]);
var nowDis = getDis(nowPoint[1], nowPoint[0]);
e.scale = nowDis / startDis;//手指移动时的距离与开始时的手指距离的比值
var startDeg = getDeg(startPoint[1], startPoint[0]);
var nowDeg = getDeg(nowPoint[1], nowPoint[0]);
e.rotation = nowDeg - startDeg;//多指旋转的角度
inti.change && inti.change.call(el, e);//手指移动时执行
}
});
el.addEventListener('touchend', function (e) {
if (isGesture) {
//e.touches:当前屏幕的手指列表 e.targetTouches:当前元素的手指列表
if (e.touches.length < 2 || e.targetTouches.length < 1) {
isGesture = false;
inti.end && inti.end.call(el, e);//手指抬起时执行
}
}
});
}
function getDis(point1, point2) {
var x = point2.x - point1.x;
var y = point2.y - point1.y;
return Math.sqrt(x * x + y * y);
}
function getDeg(point1, point2) {
var x = point2.x - point1.x;
var y = point2.y - point1.y;
return Math.atan2(y, x) * 180 / Math.PI;
}
完整demo下载 https://images-lm.oss-cn-hangzhou.aliyuncs.com/multiFinger.zip ,不足之处,请交流之,联系 qq:1033256773
若陛下您觉得满意,可随意给臣打赏,几毛几分都是对微臣的支持!