[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,只有两种大小。

posted @   wolfy  阅读(33318)  评论(4编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2015-10-10 js判断是否是PC,IOS,Android客户端
2013-10-10 Log4Net日志记录两种方式
点击右上角即可分享
微信分享提示