[js/jquery]移動端手勢拖動,放大,縮小預覽圖片


摘要

有這樣的需求需要在手機端預覽圖片的時候,實現圖片的手勢拖動,放大縮小功能。最終通過touch.js這個插件實現了效果。

touch.js

Touch.js是移動設備上的手勢識別與事件庫, 由百度雲Clouda團隊維護,也是在百度內部廣泛使用的開發工具.

Touch.js的代碼已托管於github並開源,希望能幫助國內更多的開發者學習和開發出優秀的App產品.

Touch.js手勢庫專為移動設備設計, 請在Webkit內核瀏覽器中使用.

核心代碼

imgView為圖片的容器img標簽。

   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}}">

剛開始加載的時候,讓圖片寬度跟隨屏幕的寬度自適應。這里實現的是手勢放大2,縮小時變為1,只有兩種大小。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM