- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
- <title > 原生 H5 两只手指控制图片放大缩小 </title>
- <style>
- html,body{width:98%;height:98%;overflow:hidden;position:fixed;}
- .cover {width:100%;height:100%;position:fixed;left:0;top:0;z-index:10000;display:none;}
- .cover div{position:absolute;background:#CCC;opacity:0.9;-moz-opacity:0.9;filter:alpha(opacity=90);}
- </style>
- </head>
- <body>
- <div class="cover" style="display:block;">
- <div style="width:20vw;height:100%;"></div>
- <div style="width:20vw;height:100%;left:80vw;"></div>
- <div style="width:60vw;height: 30%;left:20vw;"></div>
- <div style="width:60vw;height:100%;left:20vw;top: calc( 30% + 60vw )"></div>
- </div>
- <img style="width:100vw;position:absolute;left:0;top:0;" src="http://test.h3399.cn/uploads/imgs/201804/1523953618303.jpg" />
- <script>
- var img2;
- window.onload = function() {
- // 初始化 图片信息
- var CSS = getComputedStyle(document.querySelector('img'));
- img2 = {'width':parseInt(css.width),'height':parseInt(css.height),'top':parseInt(css.top),'left':parseInt(css.left)};
- }
- var touches=[];
- // 手指接触屏幕
- document.addEventListener('touchstart', function(e) {
- // 大于 2 个手指跳过
- if (touches.length>=2) return;
- // 没有手指时 初始化 图片信息
- if (touches.length==0) {
- var css = getComputedStyle(document.querySelector('img'));
- img2 = {'width':parseInt(css.width),'height':parseInt(css.height),'top':parseInt(css.top),'left':parseInt(css.left)};
- }
- for (var i=0;i<e.touches.length;i++) touches[e.touches[i]['identifier']] = e.touches[i];
- }, false);
- // 手指在屏幕上滑动
- document.addEventListener('touchmove',function(e) {
- // 是 1 个手指 移动
- if(touches.length==1) {
- var img = document.querySelector('img');
- img.style.left = parseFloat(e.touches[0].pageX)-parseFloat(touches[0].pageX)+img2['left']+"px";
- img.style.top = parseFloat(e.touches[0].pageY)-parseFloat(touches[0].pageY)+img2['top']+"px";
- return;
- }
- // 是 2 个手指 缩放
- if(touches.length==2) {
- // 判断手指距离
- var sx = Math.abs(touches[0].pageX - touches[1].pageX);
- var ex = Math.abs(e.touches[0].pageX - e.touches[1].pageX);
- var cx = (ex-sx)*1.6;
- var img = document.querySelector('img');
- img.style.width = (img2['width']+cx)+'px';
- return;
- }
- }, false);
- // 手指离开屏幕
- document.addEventListener('touchend', function(e) {console.log(e);
- // 删除离开的手指
- var ids = Object.keys(touches);
- for (var i=0;i<e.changedTouches.length;i++) {
- var id = e.changedTouches[i]['identifier'];
- touches.splice(ids.indexOf(id),1);
- }
- // 初始化 没离开的手指
- for (var i=0;i<e.touches.length;i++) touches[e.touches[i]['identifier']] = e.touches[i];
- var css = getComputedStyle(document.querySelector('img'));
- img2 = {'width':parseInt(css.width),'height':parseInt(css.height),'top':parseInt(css.top),'left':parseInt(css.left)};
- }, false);
- </script>
- </body>
- </html>
来源: