js/jquery移动端手势拖动,放大,缩小预览图片

有这样的需求需要在手机端预览图片的时候,实现图片的手势拖动,放大缩小功能。最终通过touch.js这个插件实现了效果。或者PinchZoom.js是一个Javript库,提供多点触摸手势缩放和拖动任何DOM元素;这里我介绍的就是touch.js

Touch.js是移动设备上的手势识别与事件库, 由百度云Clouda团队维护,也是在百度内部广泛使用的开发工具.

Touch.js的代码已托管于github并开源,希望能帮助国内更多的开发者学习和开发出优秀的App产品.

Touch.js手势库专为移动设备设计, 请在Webkit内核浏览器中使用.

var target = document.getElementById("imgView");
    target.style.webkitTransition = 'all ease 0.05s';

    touch.on('#imgView', 'touchstart', function (ev) {
        ev.preventDefault();
    });

    var initialScale = -10;
    var currentScale;
    var dx, dy;
    touch.on('#imgView', 'pinchend', function (ev) {
        if ($("#imgView").hasClass('viewerimg')) {
            $("#imgView").removeClass("viewerimg");
        };
        currentScale = ev.scale - 1;
        currentScale = initialScale + currentScale;
        currentScale = currentScale > 2 ? 2 : currentScale;
        currentScale = currentScale < 1 ? 1 : currentScale;
        if (currentScale == 1) {
            $("#imgView").addClass("viewerimg");
        };
        this.style.webkitTransform = 'scale(' + currentScale + ')';
        console.log("当前缩放比例为:" + currentScale + ".");
        
    });

    touch.on('#imgView', 'pinchend', function (ev) {
        initialScale = currentScale;
       
    });

    touch.on('#imgView', 'drag', function (ev) {
        dx = dx || 0;
        dy = dy || 0;
        this.style.webkitTransform = 'scale(' + currentScale + ')';
        console.log("当前x值为:" + dx + ", 当前y值为:" + dy + ".");
        var offx = dx + ev.x + "px";
        var offy = dy + ev.y + "px";
        this.style.webkitTransform = "translate3d(" + offx + "," + offy + ",0)";
    });

    touch.on('#imgView', 'dragend', function (ev) {
        dx += ev.x;
        dy += ev.y;
    });

  html代码

<style>
        .viewerimg {
            width: 100%;
            height: auto;
        }
    </style>
    <img id="imgView" class="viewerimg" draggable="true"src="{{img.url}}" alt="{{img.name}}" title="{{img.name}}">

  

posted on 2017-12-07 11:45  share水边  阅读(4326)  评论(0编辑  收藏  举报

导航