javascript原生移动drag效果之touch.drag.js

jerry thinkphp 2015年11月19日 收藏
手机页面的上下左右拖动效果.
详情请阅读:https://git.oschina.net/wuquanyao/touch.drag.js
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+ author:wuquanyao
//+ email:wqynqa@163.com
//+ nickname:挪威森林
//+ touch.drag-1.0.0.js,测试版
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
var Touch = {};
(function(Touch){

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //+ config参数{seletor:'',direction:1, factor:1}
    //+ selector:css选择器;
    //+ direction:0|1|2,0垂直方向,1水平方向,2综合方向;
    //+ factor:弹性因子,0到1,值越大,阻尼越大
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Touch.drag = function(config){

        config = config || {selector:'body',direction:1,factor:0.7};

        var ele,

            pos    = {x:'',y:''}, 

            press  = {x:'',y:''},

            events = ['touchstart','touchmove','touchend','touchcancel'];

        ele = document.querySelector(config['selector']);

        ele.addEventListener(events[0],function(event){
            
            event.preventDefault();

            pos['x'] = event.currentTarget.getBoundingClientRect().left;

            pos['y'] = event.currentTarget.getBoundingClientRect().top;

            press['x'] = event.touches[0].pageX;

            press['y'] = event.touches[0].pageY;

        },false);
        ele.addEventListener(events[1],function(event){

            event.preventDefault();

            if(event.targetTouches.length>1)return false;

            var move = {x:null,y:null};
            //x>0向右,x<0向左
            move['x'] = (event.touches[0].pageX - press['x'])*(1-config.factor);
            //y>0向上,y<0向下
            move['y'] = (event.touches[0].pageY - press['y'])*(1-config.factor);

            switch(config.direction){

                case 0: translate = 'translate(0,'+move['y']+'px)';
                        break;

                case 1: translate = 'translate('+move['x']+'px,0)';
                        break;

                case 2: translate = 'translate('+move['x']+'px,'+move['y']+'px)'; 
                        break;

                default:translate = 'translate('+move['x']+'px,0)';
            }

            event.currentTarget.style.webkitTransform = translate;

        },false);

        ele.addEventListener(events[2],function(event){            

            event.preventDefault();

            event.currentTarget.style.webkitTransform = 'translate('+pos['x']+'px,'+pos['y']+'px)';

        },false);
    }
})(Touch);

附件QQ截图20151027102555.png ( 150.15 KB 下载:28 次 )