手機端圖片點選預覽,雙指放大,完整demo,引入hammer.js
阿新 • • 發佈:2018-12-25
程式碼凌亂,自己寫的絕對能用!
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ padding:0px; margin:0px; } html{ height:100%; } body{ height:100%; } .main{ width: 3.75rem; position: relative; height:100%; margin: 0 auto; background: #eee } .main h1{ font-size:0.16rem; } .main img{ max-width: 100% } .box { width: 3.75rem; height:100%; background: #333; position: absolute; top:0px; left:0px; margin: 0 auto; align-items: center; /*定義body的元素垂直居中*/ justify-content: center; /*定義body的裡的元素水平居中*/ display: none; overflow: hidden } .box img{ width:100%; position: absolute; } </style> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <script type="text/javascript"> (function (doc, win) {//這段程式碼是做手機端rem適應的 var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function () { var clientWidth = docEl.clientWidth; if (clientWidth>640){ clientWidth=640 } if (!clientWidth) return; else{ docEl.style.fontSize = clientWidth / 3.75 + 'px'; } }; if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window); </script> </head> <body> <div class="main"> <h1>點選這個圖片進行預覽</h1> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545628346247&di=f2fcd4f88291e0f60d6599602ee8ab20&imgtype=jpg&src=http%3A%2F%2Fimg1.imgtn.bdimg.com%2Fit%2Fu%3D3304533311%2C1137740692%26fm%3D214%26gp%3D0.jpg"/> <div class="box"> <img src="" /> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> var pimg=document.querySelector("img"); var oImg = document.querySelector(".box img"); var oBox = document.querySelector(".box"); pimg.onclick=function(){ oBox.style.display="flex" oImg.src=pimg.src } oBox.onclick=function(){ oBox.style.display="none" oImg.src='' } var hammer = new Hammer(oImg);//hammer例項化 hammer.get('pan').set({direction: Hammer.DIRECTION_ALL});//啟用pan(移動)功能 hammer.get('pinch').set({enable: true});//啟用pinch(雙指縮放)功能 hammer.on("panstart", function(event) { var left = oImg.offsetLeft; var tp = oImg.offsetTop; hammer.on("panmove", function(event) { oImg.style.left = left + event.deltaX + 'px'; oImg.style.top = tp + event.deltaY + 'px'; }); }) hammer.on("pinchstart", function(e) { hammer.on("pinchout", function(e) { oImg.style.transition = "-webkit-transform 300ms ease-out"; oImg.style.webkitTransform = "scale(2.5)"; }); hammer.on("pinchin", function(e) { oImg.style.transition = "-webkit-transform 300ms ease-out"; oImg.style.webkitTransform = "scale(1)"; }); }) </script> </body> </html>