js移动端手势放大缩小移动图片(优化)

#msgPopover img{
        width: 100%;
        /*padding: .2rem .4rem;*/
        overflow: auto;
        position: relative;
      }


<div id="msgPopover" class="mui-popover">
      <div class="msg-img">
        <img id="msgPopoverImg" src="" />
      </div>
    </div>

touchScale($('#msgPopoverImg'), $('.msg-img'))


/**
    * $touch 需要移动放缩的img
    * $touchOriginal 控制移动放缩的区域
    **/
    function touchScale ($touch, $touchOriginal) {
      var sX, eX, sY, eY, scale, x1, x2, y1, y2, imgLeft, imgTop, imgWidth, imgHeight, one = false;
      var originalWidth = $touch.width();
      var originalHeight = $touch.height();
      var imgLeft = parseInt($touch.css('left'));
      var imgTop = parseInt($touch.css('top'));

      $touchOriginal.on('touchstart touchmove touchend', function (event) {
        var touch1 = event.originalEvent.targetTouches[0];  // 第一根手指touch事件
        var touch2 = event.originalEvent.targetTouches[1];  // 第二根手指touch事件
        var fingers = event.originalEvent.touches.length;  // 屏幕上手指数量

        // 手指放在屏幕上的时候
        if (event.type == 'touchstart') {
          if (fingers == 2) {
            // 放缩图片x轴初始
            sX = Math.abs(touch1.pageX - touch2.pageX);
            sY = Math.abs(touch1.pageY - touch2.pageY);
            one = false;
          } else {
            x1 = touch1.pageX;
            y1 = touch1.pageY;
            one = true
          }
        } else if (event.type == 'touchmove') {
          // 手指移动过程
          if (fingers == 2) {
            // 放缩图片x轴
            eX = Math.abs(touch1.pageX - touch2.pageX);
            eY = Math.abs(touch1.pageY - touch2.pageY);
            // 为了放缩更加便捷,取最大的绝对值
            scale = Math.abs(eX - sX) > Math.abs(eY - sY) ? eX - sX : eY - sY;
            $touch.css({
              'width': originalWidth + scale,
              'height': originalHeight + scale
            })
          } else if (one) {
            // 错位控制,放缩未结束不允许移动位置
            x2 = touch1.pageX;
            y2 = touch1.pageY;
            $touch.css({
              'top': imgTop + y2 - y1,
              'left': imgLeft + x2 - x1
            })
          }
        } else if (event.type == 'touchend') {
          // 放缩结束
          originalWidth = $touch.width();
          originalHeight = $touch.height();
          imgLeft = parseInt($touch.css('left'));
          imgTop = parseInt($touch.css('top'));
        }
      });
    }

引用资料:

1.js实现移动端手势放大缩小图片

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值