为了账号安全,请及时绑定邮箱和手机立即绑定

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

摘要

有这样的需求需要在手机端预览图片的时候,实现图片的手势拖动,放大缩小功能。最终通过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"class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{{img.url}}" alt="{{img.name}}" title="{{img.name}}">


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

点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消