移动端触屏实现元素拖拽功能

/*
 * 手指拖拽
 * options参数控制水平或垂直方向是否可以拖拽
 */
function drag(el, options) {
    
    
    options.x = typeof options.x !== 'undefined' ? options.x : true; //x方向是否允许拖拽
    options.y = typeof options.y !== 'undefined' ? options.y : false; //y方向是否允许拖拽

    if (!options.x && !options.y) return;

    //当前点的坐标
    var curPoint = {
    
    
        x: 0,
        y: 0,
    };

    //手指按下点坐标
    var downPoint = {
    
    };

    //本次手指按下是否有滑动
    var isTouchMove = false;

    el.addEventListener('touchstart', handleStart, false);
    el.addEventListener('touchmove', handleMove, false);
    el.addEventListener('touchend', handleEnd, false);

    function handleStart(ev) {
    
    
        var touch = ev.changedTouches[0];
        downPoint.x = touch.pageX;
        downPoint.y = touch.pageY;
    }

    function handleMove(ev) {
    
    
        //解决拖拽时与页面滚动条的冲突
        ev.preventDefault();

        isTouchMove = true;

        var touch = ev.changedTouches[0];

        //移动的距离
        var distance = {
    
    };

        //移动到最终点位置坐标
        var movePoint = {
    
    
            x: 0,
            y: 0,
        };

        //水平方向移动的距离
        distance.x = touch.pageX - downPoint.x;
        //垂直方向移动的距离
        distance.y = touch.pageY - downPoint.y;

        if (options.x) {
    
    
            movePoint.x = distance.x + curPoint.x;
        }
        if (options.y) {
    
    
            movePoint.y = distance.y + curPoint.y;
        }

        move(el, movePoint.x, movePoint.y);
    }

    function handleEnd(ev) {
    
    
        if (!isTouchMove) {
    
    
            //没有移动则不更新当前点的位置信息
            return;
        }
        var touch = ev.changedTouches[0];
        curPoint.x += touch.pageX - downPoint.x;
        curPoint.y += touch.pageY - downPoint.y;
        isTouchMove = false;
    }

    function move(el, x, y) {
    
    
        x = x || 0; //x没传默认给0
        y = y || 0; //y没传默认给0
        //使用translate3d在移动端会开启GPU加速,性能更高
        el.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0)';
    }
}

猜你喜欢

转载自blog.csdn.net/sqf251877543/article/details/108490821