Last active
April 23, 2020 04:22
-
-
Save fj-auto/b010034b28bb7b116a07 to your computer and use it in GitHub Desktop.
移动端web伸缩方案
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dpr, rem, scale, | |
docElem = document.documentElement, | |
fontElem = document.createElement('style'), | |
metaElem = document.querySelector('meta[name="viewport"]'); | |
dpr = window.devicePixelRatio || 1; // 获取屏幕dpi, default设为1 | |
rem = docElem.clientWidth * dpr / 10; // 根据屏幕宽度和dpr来动态计算base 'rem' font-size, 取10是为了好计算 | |
scale = 1 / dpr; // 不用再傻傻的拿[设计稿/2]; | |
// 同时也处理retina屏幕下border: 1px的情况; | |
// 屏幕适配布局问题; | |
// 也能实现图片高清方案. | |
// metaElem.setAttribute('content', 'width=' + dpr * docElem.clientWidth + ', user-scalable=no , initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale); | |
// 加入shrink-to-fit=no是防止IOS9引进的shrink-to-fix特性bug! | |
metaElem.setAttribute('content', 'width=' + dpr * docElem.clientWidth + ', initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no, shrink-to-fit=no'); | |
// 设置data-dpr属性, 留作的css hack之用 | |
docElem.setAttribute('data-dpr', dpr); | |
// 把动态计算出来的Base 'rem' font-size写入<html> tag | |
docElem.setAttribute('style', 'font-size:' + rem + 'px;') | |
// 根据不同dpr对<body> font-size进行等比设置 | |
// 这个可以在css/sass里面完成 ex: [data-dpr="2"] body {font-size: 32px}; | |
// 在这里做处理,是防止在css没有加载过来时候页面字体太大的情况 | |
// 这里 32 是说,这边假定你的body base font-size 为16px. (brower default font-size 也为16px) | |
docElem.firstElementChild.appendChild(fontElem); | |
switch (dpr) { | |
case 2: | |
rem = Math.round(32 * 2 / 2); | |
break; | |
// for mx3 | |
case 2.5: | |
rem = Math.round(32 * 2.5 / 2); | |
break; | |
// for 小米note | |
case 2.75: | |
rem = Math.round(32 * 2.75 / 2); | |
break; | |
case 3: | |
rem = Math.round(32 * 3 / 2); | |
break; | |
// for 三星note4 | |
case 4: | |
rem = Math.round(32 * 4 / 2); | |
break; | |
} | |
fontElem.innerHTML = 'body{font-size:' + rem + 'px!important;}'; | |
// 给js调用的, 某一dpr下rem和px之间的转换函数 | |
window.rem2px = function(v) { | |
v = parseFloat(v); | |
return v * rem; | |
}; | |
window.px2rem = function(v) { | |
v = parseFloat(v); | |
return v / rem; | |
}; | |
window.dpr = dpr; | |
window.rem = rem; | |
// 这个方法来源于: http://div.io/topic/1092 | |
// 这边做了一点小处理 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment