1. 程式人生 > >插件-模仿滑動動作事件

插件-模仿滑動動作事件

動作 use roi start mouse time() define 垂直 tel

前端頁面經常用到滑動事件,即判斷是動作左滑、右滑、上滑或者下滑,然後根據事件類型完成不同的功能,最常見的就是H5的翻頁,如果需要的事件很簡單,就是判斷一下滑動方向然後執行回調函數,那麽如果引用較大的插件將會十分影響頁面的加載速度。

下面就分享一個簡單的滑動事件的插件,輕量好用。

直接貼代碼

var TouchTool = function(param) {
    var self = this;
    this.dh = document.documentElement.clientHeight;
    this.direction = param.direction || ‘vertical‘;
    
this.device = /android|iphone|ipad|ipod|webos|iemobile|opear mini|linux/i.test(navigator.userAgent.toLowerCase()); this.sx = this.sy = this.ex = this.ey = this.mx = this.my = this.speedx = this.speedy = this.st = this.et = 0; this.obj = param.obj; this.len = this.obj.length; this.startEvtName = this
.device ? "touchstart" : "mousedown"; this.moveEvtName = this.device ? "touchmove" : "mousemove"; this.endEvtName = this.device ? "touchend" : "mouseup"; console.log(this.obj) this.touchStart = function(e) { var e = e || event; self.st = new Date().getTime(); self.sx
= self.device ? e.touches[0].clientX : e.clientX; self.sy = self.device ? e.touches[0].clientY : e.clientY; self.obj.addEventListener(self.moveEvtName, self.touchMove); self.obj.addEventListener(self.endEvtName, self.touchEnd); } this.touchMove = function(e) { var e = e || event; self.ex = self.device ? e.touches[0].clientX : e.clientX; self.ey = self.device ? e.touches[0].clientY : e.clientY; } this.touchEnd = function(e) { var e = e || event; self.et = new Date().getTime(); self.obj.removeEventListener(self.moveEvtName, self.touchMove); self.obj.removeEventListener(self.endEvtName, self.touchEnd); self.ex = self.ex; self.ey = self.ey; self.mx = self.ex - self.sx; self.my = self.ey - self.sy; self.speedx = Math.abs(self.mx / (self.et - self.st)); self.speedy = Math.abs(self.my / (self.et - self.st)); if(self.direction == ‘horizontal‘) { if((self.speedx > 1 || (self.speedx > 0.5 && Math.abs(self.mx) > 250)) && self.mx > 0) { if(typeof param.slideRight != ‘undefined‘) { param.slideRight(); } }; if((self.speedx > 1 || (self.speedx > 0.5 && Math.abs(self.mx) > 250)) && self.mx < 0) { if(typeof param.slideLeft != ‘undefined‘) { param.slideLeft(); } }; } if(self.direction == ‘vertical‘) { if((self.speedy > 1 || (self.speedy > 0.5 && Math.abs(self.my) > 300)) && self.my > 0) { if(typeof param.slideDown != ‘undefined‘) { param.slideDown(); } }; if((self.speedy > 1 || (self.speedy > 0.5 && Math.abs(self.my) > 300)) && self.my < 0) { if(typeof param.slideUp != ‘undefined‘) { param.slideUp(); } } } } this.obj.addEventListener(this.startEvtName, this.touchStart); }

使用方法:

new TouchTool({
    ‘obj‘: document.getElementById(‘touchBox‘),
    ‘direction‘: ‘vertical‘, //horizontal水平 vertical垂直
    ‘slideUp‘: function() {
        console.log(‘u‘)
    },
    ‘slideDown‘: function() {
        console.log(‘d‘)
    },
    ‘slideLeft‘: function() {
        console.log(‘l‘)
    },
    ‘slideRight‘: function() {
        console.log(‘r‘)
    }
})

在配置參數裏填入要執行的回調函數,就可以使用了,PC端和移動端都適用,很簡單有木有

(完)

插件-模仿滑動動作事件