亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

移動端手勢拖動,放大,縮小預覽圖片

摘要

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

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消