移動端使用 zepto 作一些基於觸摸的動畫的時候,須要開發一個函數庫。html
功能:實例化對象之後可以,觸發相應的事件,可以返回給我,當前的移動方向和 X 軸 或者 Y 軸 的移動位移。git
var TouchDirection = function(e) { var startThat = {}, moveThat = {}; this.touchStartEven = function(e) { startThat.startX = e.touches[0].pageX; startThat.startY = e.touches[0].pageY; this.startThat = startThat; return this; }; this.touchMoveEven = function(e) { moveX = e.touches[0].pageX; moveY = e.touches[0].pageY; tempX = this.startThat.startX - moveX; tempY = this.startThat.startY - moveY; absTempX = Math.abs(tempX); absTempY = Math.abs(tempY); angleTouch = absTempX / absTempY; if (tempX < 0 && angleTouch >= 1) { //鼠標右滑動 moveThat.direction = 'right'; moveThat.moveX = absTempX; this.moveThat = moveThat; return this; } if (tempX > 0 && angleTouch >= 1) { //鼠標左滑動 moveThat.direction = 'left'; moveThat.moveX = absTempX; this.moveThat = moveThat; return this; } if (tempY > 0 && angleTouch < 1) { //上滑 moveThat.direction = 'up'; moveThat.moveY = absTempY; this.moveThat = moveThat; return this; } if (tempY < 0 && angleTouch < 1) { //下滑 moveThat.direction = 'down'; moveThat.moveY = absTempY; this.moveThat = moveThat; return this; } }; this.touchEndEven = function(){ this.startThat = null; this.moveThat = null; }; };
使用方法:github
var touchResult = new TouchDirection(); var touchStartEv = function(e){ var that = touchResult.touchStartEven(e); console.log(that.startThat); }; var touchMoveEv = function(e) { var that = touchResult.touchMoveEven(e); console.log(that.moveThat); }; var touchEndEv = function(e) { var that = touchResult.touchEndEven(e); }; $('.test').on('touchstart', touchStartEv); $('.test').on('touchmove', touchMoveEv); $('.test').on('touchend', touchEndEv);
測試的運行結果:api
實例 demo 地址:點我函數
若是您以爲對您有幫助,請點擊下面的 star 給我一顆星。謝謝啦! 測試