Skip to content

Instantly share code, notes, and snippets.

@ddoctorx
Last active February 2, 2016 10:29
Show Gist options
  • Save ddoctorx/7328997f2e7a134ccc77 to your computer and use it in GitHub Desktop.
Save ddoctorx/7328997f2e7a134ccc77 to your computer and use it in GitHub Desktop.
移动Web伸缩方案
(function() {
var dpr, rem, scale,
resize = 'orientationchange' in window ? 'orientationchange' : 'resize',
docElem = document.documentElement,
fontElem = document.createElement('style'),
metaElem = document.querySelector('meta[name="viewport"]');
dpr = docElem.clientWidth >= 540 ? 1 : window.devicePixelRatio || 1;
rem = docElem.clientWidth * dpr / 10;
scale = 1 / dpr;
function setAttrs() {
docElem.setAttribute('data-dpr', dpr);
docElem.setAttribute('style', 'font-size:' + rem + 'px;')
}
setAttrs();
window.addEventListener(resize, function() {
if (dpr !== 1) return;
rem = docElem.clientWidth >= 540 ? 540 * dpr / 10 : docElem.clientWidth * dpr / 10;
setAttrs();
}, false);
document.addEventListener('DOMContentLoaded', function() {
if (dpr === 1 && docElem.clientWidth >= 540) {
docElem.setAttribute('style', 'font-size:' + 54 + 'px;');
}
}, false);
metaElem.setAttribute('content', 'width=' + dpr * docElem.clientWidth + ', initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no, shrink-to-fit=no');
docElem.firstElementChild.appendChild(fontElem);
switch (dpr) {
case 1:
rem = Math.round(32 / 2);
break;
// for mx3
case 2.5:
rem = Math.round(32 * 2.5 / 2);
break;
// for Nexus 5X
case 2.625:
rem = Math.round(32 * 2.625 / 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;
default:
rem = Math.round(32 * 2 / 2);
}
fontElem.innerHTML = 'body{font-size:' + rem + 'px!important;}';
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment