栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

摘要

有这样的需求需要在手机端预览图片的时候,实现图片的手势拖动,放大缩小功能。最终通过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代码


  
       .viewerimg {
           width: 100%;
           height: auto;
       }
   
   


刚开始加载的时候,让图片宽度跟随屏幕的宽度自适应。这里实现的是手势放大2,缩小时变为1,只有两种大小。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/245909.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号