移动端viewport加rem适配
注:必须使用scss或者less预编译
1,调取dpr+屏幕宽度,设置html参考fontSize,和body默认像素
1 (function (window, document) { 2 function resizeFn() { 3 /** 4 * initQuery 设计稿参数,如果设计稿有变化,则此处需要修改 5 * */ 6 7 var initQuery = { 8 designWidth: 750, 9 fontSize: 26 10 }, 11 reg = /(iPhone|iPad|ios|Android)/ig, 12 nav = window.navigator.userAgent, 13 meta = document.createElement('meta'), 14 head = document.querySelector('head'), 15 dpr = window.devicePixelRatio, 16 width = window.screen.width, 17 height = window.screen.height, 18 html = document.getElementsByTagName('html')[0], 19 body = document.body || document.getElementsByTagName('body'); 20 21 if (!reg.test(nav)) { 22 /* 23 * 非移动端 24 * */ 25 var vpt = document.querySelector('[data-vpt]'); 26 if (vpt) { 27 vpt.parentNode.removeChild(vpt); 28 body.removeAttribute('style'); 29 html.removeAttribute('style'); 30 } 31 return 32 } 33 if (width > height) { 34 width = height; 35 } 36 meta.setAttribute('name', 'viewport'); 37 meta.setAttribute('data-vpt', '0'); 38 meta.setAttribute('content', "width=device-width,initial-scale=" + 1 / dpr + ",user-scalable=0"); 39 head.appendChild(meta); 40 html.style.fontSize = ((width / 10) * dpr) / 2 + 'px'; 41 body.style.fontSize = (20 / initQuery.designWidth) * initQuery.fontSize + 'rem'; 42 } 43 44 resizeFn(); 45 window.addEventListener('resize', resizeFn); 46 })(window, document)
2,写scss 的px转rem方法,或者webpack里面配置,以下提供scss方法,后期补充webpack配置
1 @function pxToRem($px){ 2 @return (20/750)*$px+rem //该处的750也是设计稿提供,20是上面js代码计算出来的,20rem为750px 3 }
浙公网安备 33010602011771号