博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript移动端滑动操作封装
阅读量:6548 次
发布时间:2019-06-24

本文共 2431 字,大约阅读时间需要 8 分钟。

/** * Created by Farris on 2018-08-20. */export default class Slide {    constructor(element, range) {        this.element = element;    //目标DOM元素        this.range = range || 20;  //滑动距离,大于或者等于这个值时才算有效的滑动        this.moving = false;        this.startX = 0;        this.startY = 0;        this.endX = 0;        this.endY = 0;    }    slideUp(callback) {        this.slide("up", callback);    }    slideDown(callback) {        this.slide("down", callback);    }    slideLeft(callback) {        this.slide("left", callback);    }    slideRight(callback) {        this.slide("right", callback);    }    slide(direction, callback) {        this.element.addEventListener('touchstart', e => this.touchstart(e), false);        this.element.addEventListener('touchmove', e => this.touchmove(e), false);        this.element.addEventListener('touchend', e => this.touchend(direction, callback, e), false);    }    touchstart(e) {        let touches = e.touches[0];        let {clientX, clientY} = touches;        [this.startX, this.startY] = [clientX, clientY];        this.moving = false;    }    touchmove(e) {        this.moving = true;    }    touchend(direction, callback, e) {        if (!this.moving) {            return;        }        let cb = (...args) => typeof callback === "function" && callback(...args);        let touches = e.changedTouches[0];        let {clientX, clientY} = touches;        [this.endX, this.endY] = [clientX, clientY];        let distanceX = this.startX - this.endX;        let distanceY = this.startY - this.endY;        let action = Math.abs(distanceX) >= Math.abs(distanceY) ? "left-right" : "up-down";        if (action === "left-right") {            if (distanceX < -this.range) {                direction === "right" && cb();            } else if (distanceX > this.range) {                direction === "left" && cb();            }        } else if (action === "up-down") {            if (distanceY < -this.range) {                direction === "down" && cb();            } else if (distanceY > this.range) {                direction === "up" && cb();            }        }    }}复制代码

使用const app = new Slide(document.getElementById("app"), 30);app.slideDown(() => {    console.log("下滑~~~~~")});app.slideUp(() => {    console.log("上滑~~~~~")});app.slideLeft(() => {    console.log("左滑~~~~~")});app.slideRight(() => {    console.log("右滑~~~~~")});复制代码

转载于:https://juejin.im/post/5b7a7fd8e51d4538dd08d03d

你可能感兴趣的文章
rpc远程调用开发
查看>>
复习-css控制文本字体属性
查看>>
学习设计模式——观察者模式
查看>>
什么是centos 的epel源
查看>>
删除LVM步骤
查看>>
Zookeeper客户端
查看>>
linux常用指令
查看>>
Servlet Demo
查看>>
Struts2中的<s:action>标签
查看>>
Java中取某一个范围的随机数
查看>>
一条复杂SQL实现思路
查看>>
我的友情链接
查看>>
android app 退出时提示确认
查看>>
win10 配置
查看>>
java 编译100个范例
查看>>
Session Cookie ServletContext
查看>>
单点登录SSO
查看>>
遇见有的软件开启后画面模糊怎么解决
查看>>
好系统重装助手教你怎么识别固态硬盘还是机械硬盘
查看>>
170. js中获取随机数 (记录一下)
查看>>