移动端滑动操作学习

(function(window,document){
    var Slide = function(box,judge,fun){
        if (!(this instanceof Slide)) return new Slide(box,judge,fun);
        var startx,starty;
        box.addEventListener("touchstart", function(e) {
            e.preventDefault(); // 阻止浏览器默认事件
            startx = parseInt(e.touches[0].pageX);
            starty = parseInt(e.touches[0].pageY);//获取滑动开始的X,Y值
        }, false);
        box.addEventListener("touchend", function(e) {
            e.preventDefault(); // 阻止浏览器默认事件
            var endx, endy;
            endx = parseInt(e.changedTouches[0].pageX);
            endy = parseInt(e.changedTouches[0].pageY);//获取滑动结束的X,Y值
            var absx =startx-endx; 
            var absy =starty-endy;
            //console.log(absx,absy,absy,3)
            if(judge=="about" || judge=="aboutupdown"){
                //检测左右滑动
                if(Math.abs( absx)>Math.abs(absy)&&Math.abs(absy)>=3){
                    if(absx>0){
                        fun.leftslide();
                    }else {
                        fun.rightslide();
                    }
                }
            }
            if(judge=="updown" || judge=="aboutupdown"){
                //检测上下滑动
                if(Math.abs( absy)>Math.abs(absx)&&Math.abs(absx)>=3){
                    if(absy>0){
                        fun.topslide()
                    }else {
                        fun.bottomslide()
                    }
                }
            }
        })
    }
    window.Slide = Slide;
})(window,document)

调用方法

 //第一个参数为DOM对象
        Slide(box,"about",{//第二个参数有三个值:左右滑动:about,上下滑动:updown,上下左右:aboutupdown
            leftslide:function(){//第三个参数可传入滑动后的操作方法
                alert("向左滑動了")
            },
            rightslide:function(){
                alert("向右滑動了")
            },
            topslide:function(){
                alert("向上滑動了")
            },
            bottomslide:function(){
                alert("向下滑動了")
            }
        })

猜你喜欢

转载自www.cnblogs.com/xueyunNO1/p/10136384.html