說在前面
上篇文章說了ios上的多指操作,那爲什麼不放在一起,把安卓的也一起講了,因爲安卓的存在兼容問題,gesturestart,gesturechange等事件安卓上都是沒有的,這些只存在於ios設備上,所以這些事件安卓設備上無效,需要自己封裝。
第一步:定義一個匿名自執行函數
匿名自執行函數的優勢在前面的文章有,這裏不多說。
(function (w) {
})(window);
第二步: 基本架構實現
(function (w) {
//給w gesture 方法
w.gesture = function (ele,callback) {
}
})();
第三步: 添加封裝的功能函數
(function (w) {
//給w gesture 方法
w.gesture = function (ele,callback) {
let isStart = false;
//判斷是否觸發了觸摸事件
ele.addEventListener('touchstart',function (event) {
if(event.touches.length >= 2){
isStart = true ;
//記錄兩個觸點間的初始距離
this.startDistance =getDistance(event.touches[0],event.touches[1]);
//記錄兩個觸點的初始角度
this.startDeg =getDeg(event.touches[0],event.touches[1]);
//判斷是否傳入回調,調用回調函數
if(callback && typeof callback['start'] === "function"){
callback['start']();
}
}
});
ele.addEventListener('touchmove',function (event) {
//判斷移動時屏幕上的觸點個數
if(event.touches.length >= 2){
//計算兩個觸點的實時距離
const currDistance = getDistance(event.touches[0], event.touches[1]);
//記錄兩個觸點的實時角度
const currDeg = getDeg(event.touches[0], event.touches[1]);
//計算實時距離與初始距離的比例,傳入event的屬性中
event.scale = currDistance / this.startDistance;
//計算實時角度與初始角度的差值,傳入event的屬性中
event.rotation = currDeg - this.startDeg;
//判斷是否傳入回調,調用回調函數
if(callback && typeof callback['change'] === "function"){
//將event傳回去
callback['change'](event);
}
}
});
// 手指離開當前元素時,先判斷當前的觸點是否小於2,是否曾觸發過touchstart事件
ele.addEventListener('touchend',function (event) {
if(event.touches.length < 2 && isStart){
//此時調用end回調
if (callback && typeof(callback['change']) === 'function') {
callback['end']();
}
//重置isStart爲false
isStart = false;
}
});
// 獲取兩個點之間的距離
function getDistance(touch1,touch2) {
const a = touch1.clientX - touch2.clientX;
const b = touch1.clientY - touch2.clientY;
//勾股定理,得出兩點距離長度
return Math.sqrt(a * a + b * b);
}
// 獲取兩個觸點的角度
function getDeg(touch1,touch2) {
const x = touch1.clientX - touch2.clientX;
const y = touch1.clientY - touch2.clientY;
//tan值 = 對邊Y / 臨邊X
const radian = Math.atan2(y, x);
return radian * 180 / Math.PI;
}
}
})();
那麼,這個庫就已經封裝好了,引入調用就ok
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Document</title>
<style>
#con{
width: 300px;
height: 300px;
line-height: 100px;
text-align: center;
font-size: 48px;
color: black;
position: absolute;
top: 50px;
left: 50px;
background: greenyellow;
}
</style>
<script src="./android.js"></script>
</head>
<body>
<div id="con">
</div>
<script>
var con = document.getElementById('con');
gesture(con,{
start:function () {
// alert("觸發了多指操作")
},
change:function (event) {
alert("移動了")
}
})
</script>
</body>
</html>
這裏只是簡單的處理,大家可以在此基礎上再進行優化和新功能添加。