移动端、PC端ontouchstart、mousedown等兼容方法(/jquery/原生)

时间:2025-01-21 08:09:34

最近项目涉及移动端手势(画div,拖拽、双指缩放、上滑删除等),我用的。  参考地址:

/

/p/0b0b9364f967

想要同时兼容移动端和pc端,实现鼠标(手指)按下并获得坐标,移动,抬起过程。

移动端支持的点击事件:

ontouchstart();
ontouchmove();
ontouchend();

PC端支持的点击事件:

onmousedown();
onmousemove();
onmouseup();

一、以 的pan事件为例:

    var oBox = ('main-cont');
    var hammer_windowsDiv = new Hammer(oBox);
    hammer_windowsDiv.get('pan').set({enable: true});

    hammer_windowsDiv.on("panstart panmove panend", function (ev) {
        switch () {
            case "panstart":
                ...
                break;
            case "panmove":
                ...
                break;
            case "panend":
                ...
                break;
        }
    })

二、原生绑定:

    var x1, x2, y1, y2;    //按下坐标和移动时的坐标    
    var oBox = ('main-cont');
     =  = function (e) {
        e = e || ;
        if ( == 'touchstart') {//移动端
            x1 = [0].clientX;
            y1 = [0].clientY;
        } else if ( == 'mousedown') {//pc端
            x1 = ;
            y1 = ;
        }
         =  = function (e) {
            if ( == 'touchmove') {//移动端
                x2 = [0].clientX;
                y2 = [0].clientY;
            } else if ( == 'mousemove') {//pc端
                x2 = ;
                y2 = ;
            }
        }
         =  = function (e) {
            ...
        }
    }

三、jquery绑定:

    var x1, x2, y1, y2;    //按下坐标和移动时的坐标
    $('#main-cont').on('touchstart mousedown',function (e) {
        e = e || ;
        if ( == 'touchstart') {
            x1 = [0].clientX; //与原生有区别
            y1 = [0].clientY;
        } else if ( == 'mousedown') {
            x1 = ;
            y1 = ;
        }
        $('#main-cont').on('touchmove mousemove',function (e) {
            if ( == 'touchmove') {
                x2 = [0].clientX;
                y2 = [0].clientY;
            } else if ( == 'mousemove') {
                x2 = ;
                y2 = ;
            }
        }
        $(document).on('touchend mouseup',function (e) {
            ...
        })
    })

以上是我实现功能的大概思路,有问题欢迎指正!