移动端和平板适配方案总结(不断更新中...)

采用手淘方案,引入flexible.debug.js,源码如下:

  1 ;(function(win, lib) {
  2     var doc = win.document;
  3     var docEl = doc.documentElement;
  4     var metaEl = doc.querySelector('meta[name="viewport"]');
  5     var flexibleEl = doc.querySelector('meta[name="flexible"]');
  6     var dpr = 0;
  7     var scale = 0;
  8     var tid;
  9     var flexible = lib.flexible || (lib.flexible = {});
 10     
 11     if (metaEl) {
 12         console.warn('将根据已有的meta标签来设置缩放比例');
 13         var match = metaEl.getAttribute('content').match(/initial-scale=([d.]+)/);
 14         if (match) {
 15             scale = parseFloat(match[1]);
 16             dpr = parseInt(1 / scale);
 17         }
 18     } else if (flexibleEl) {
 19         var content = flexibleEl.getAttribute('content');
 20         if (content) {
 21             var initialDpr = content.match(/initial-dpr=([d.]+)/);
 22             var maximumDpr = content.match(/maximum-dpr=([d.]+)/);
 23             if (initialDpr) {
 24                 dpr = parseFloat(initialDpr[1]);
 25                 scale = parseFloat((1 / dpr).toFixed(2));    
 26             }
 27             if (maximumDpr) {
 28                 dpr = parseFloat(maximumDpr[1]);
 29                 scale = parseFloat((1 / dpr).toFixed(2));    
 30             }
 31         }
 32     }
 33 
 34     if (!dpr && !scale) {
 35         var isAndroid = win.navigator.appVersion.match(/android/gi);
 36         var isIPhone = win.navigator.appVersion.match(/iphone/gi);
 37         var devicePixelRatio = win.devicePixelRatio;
 38         if (isIPhone) {
 39             // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案
 40             if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {                
 41                 dpr = 3;
 42             } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){
 43                 dpr = 2;
 44             } else {
 45                 dpr = 1;
 46             }
 47         } else {
 48             // 其他设备下,仍旧使用1倍的方案
 49             dpr = 1;
 50         }
 51         scale = 1 / dpr;
 52     }
 53 
 54     docEl.setAttribute('data-dpr', dpr);
 55     if (!metaEl) {
 56         metaEl = doc.createElement('meta');
 57         metaEl.setAttribute('name', 'viewport');
 58         metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
 59         if (docEl.firstElementChild) {
 60             docEl.firstElementChild.appendChild(metaEl);
 61         } else {
 62             var wrap = doc.createElement('div');
 63             wrap.appendChild(metaEl);
 64             doc.write(wrap.innerHTML);
 65         }
 66     }
 67 
 68     function refreshRem(){
 69         var width = docEl.getBoundingClientRect().width;
 70         if (width / dpr > 540) {
 71             width = 540 * dpr;
 72         }
 73         var rem = width / 7.5;
 74         docEl.style.fontSize = rem + 'px';
 75         flexible.rem = win.rem = rem;
 76     }
 77 
 78     win.addEventListener('resize', function() {
 79         clearTimeout(tid);
 80         tid = setTimeout(refreshRem, 300);
 81     }, false);
 82     win.addEventListener('pageshow', function(e) {
 83         if (e.persisted) {
 84             clearTimeout(tid);
 85             tid = setTimeout(refreshRem, 300);
 86         }
 87     }, false);
 88 
 89     if (doc.readyState === 'complete') {
 90         doc.body.style.fontSize = 12 * dpr + 'px';
 91     } else {
 92         doc.addEventListener('DOMContentLoaded', function(e) {
 93             doc.body.style.fontSize = 12 * dpr + 'px';
 94         }, false);
 95     }
 96     
 97 
 98     refreshRem();
 99 
100     flexible.dpr = win.dpr = dpr;
101     flexible.refreshRem = refreshRem;
102     flexible.rem2px = function(d) {
103         var val = parseFloat(d) * this.rem;
104         if (typeof d === 'string' && d.match(/rem$/)) {
105             val += 'px';
106         }
107         return val;
108     }
109     flexible.px2rem = function(d) {
110         var val = parseFloat(d) / this.rem;
111         if (typeof d === 'string' && d.match(/px$/)) {
112             val += 'rem';
113         }
114         return val;
115     }
116 
117 })(window, window['lib'] || (window['lib'] = {}));
View Code

页头加入这几行代码

<meta charset="utf-8">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="yes" name="apple-touch-fullscreen">
<meta content="telephone=no,email=no" name="format-detection">

此代码只适用于手机,如果想要继续适配平板,删除选中代码即可。

手淘还有个js文件flexible_css.debug.js是重置移动端css样式的,源码如下:

 1 (function () {
 2     // flexible.css
 3     var cssText = "" +
 4 "@charset "utf-8";html{color:#000;background:#fff;overflow-y:scroll;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}html *{outline:0;-webkit-text-size-adjust:none;-webkit-tap-highlight-color:rgba(0,0,0,0)}html,body{font-family:sans-serif}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td,hr,button,article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{margin:0;padding:0}input,select,textarea{font-size:100%}table{border-collapse:collapse;border-spacing:0}fieldset,img{border:0}abbr,acronym{border:0;font-variant:normal}del{text-decoration:line-through}address,caption,cite,code,dfn,em,th,var{font-style:normal;font-weight:500}ol,ul{list-style:none}caption,th{text-align:left}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:500}q:before,q:after{content:''}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}a:hover{text-decoration:underline}ins,a{text-decoration:none}";
 5     // cssText end
 6 
 7     var styleEl = document.createElement("style");
 8     document.getElementsByTagName("head")[0].appendChild(styleEl);
 9     if (styleEl.styleSheet) {
10         if (!styleEl.styleSheet.disabled) {
11             styleEl.styleSheet.cssText = cssText;
12         }
13     } else {
14         try {
15             styleEl.innerHTML = cssText
16         } catch(e) {
17             styleEl.innerText = cssText;
18         }
19     }
20 }());
View Code

此文件主要是重置css样式,对页面效果要求较高的可以引入,有人对这两个js文件整合到了一个js文件中,源码如下:

1 !function(){var a="@charset "utf-8";html{overflow-y:scroll;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}html *{outline:0;-webkit-text-size-adjust:none;-webkit-tap-highlight-color:rgba(0,0,0,0)}html,body{}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td,hr,button,article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{margin:0;padding:0}input,select,textarea{font-size:100%}table{border-collapse:collapse;border-spacing:0}fieldset,img{border:0}abbr,acronym{border:0;font-variant:normal}del{text-decoration:line-through}address,caption,cite,code,dfn,em,th,var{font-style:normal;font-weight:500}ol,ul{list-style:none}caption,th{text-align:left}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:500}q:before,q:after{content:''}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}a:hover{text-decoration:underline}ins,a{text-decoration:none}",b=document.createElement("style");if(document.getElementsByTagName("head")[0].appendChild(b),b.styleSheet)b.styleSheet.disabled||(b.styleSheet.cssText=a);else try{b.innerHTML=a}catch(c){b.innerText=a}}();!function(a,b){function c(){var b=f.getBoundingClientRect().width;b/i>540&&(b=540*i);var c=b/7.5;f.style.fontSize=c+"px",k.rem=a.rem=c}var d,e=a.document,f=e.documentElement,g=e.querySelector('meta[name="viewport"]'),h=e.querySelector('meta[name="flexible"]'),i=0,j=0,k=b.flexible||(b.flexible={});if(g){console.warn("将根据已有的meta标签来设置缩放比例");var l=g.getAttribute("content").match(/initial-scale=([d.]+)/);l&&(j=parseFloat(l[1]),i=parseInt(1/j))}else if(h){var m=h.getAttribute("content");if(m){var n=m.match(/initial-dpr=([d.]+)/),o=m.match(/maximum-dpr=([d.]+)/);n&&(i=parseFloat(n[1]),j=parseFloat((1/i).toFixed(2))),o&&(i=parseFloat(o[1]),j=parseFloat((1/i).toFixed(2)))}}if(!i&&!j){var p=(a.navigator.appVersion.match(/android/gi),a.navigator.appVersion.match(/iphone/gi)),q=a.devicePixelRatio;i=p?q>=3&&(!i||i>=3)?3:q>=2&&(!i||i>=2)?2:1:1,j=1/i}if(f.setAttribute("data-dpr",i),!g)if(g=e.createElement("meta"),g.setAttribute("name","viewport"),g.setAttribute("content","initial-scale="+j+", maximum-scale="+j+", minimum-scale="+j+", user-scalable=no"),f.firstElementChild)f.firstElementChild.appendChild(g);else{var r=e.createElement("div");r.appendChild(g),e.write(r.innerHTML)}a.addEventListener("resize",function(){clearTimeout(d),d=setTimeout(c,300)},!1),a.addEventListener("pageshow",function(a){a.persisted&&(clearTimeout(d),d=setTimeout(c,300))},!1),"complete"===e.readyState?e.body.style.fontSize=12*i+"px":e.addEventListener("DOMContentLoaded",function(){e.body.style.fontSize=12*i+"px"},!1),c(),k.dpr=a.dpr=i,k.refreshRem=c,k.rem2px=function(a){var b=parseFloat(a)*this.rem;return"string"==typeof a&&a.match(/rem$/)&&(b+="px"),b},k.px2rem=function(a){var b=parseFloat(a)/this.rem;return"string"==typeof a&&a.match(/px$/)&&(b+="rem"),b}}(window,window.lib||(window.lib={}));
View Code

同理,要想适配手机和平板,删除这行代码即可;

b / i > 540 && (b = 540 * i);

适配的js文件最好不要用require.js和sea.js加载,适配最好是放在最开始的位置加载,不然页面打开的最开始瞬间会因为没有加载适配文件导致页面乱掉。

原文地址:https://www.cnblogs.com/yangyang03/p/5069053.html