常见的手机屏幕的分辨率各种各样,根据手机屏幕控制像素实现屏幕自适应。
<script>
(function () {
var standardDpi, dpi, w, scale, text;
w = window.screen.width;
if (w > 0) {
if (w < 320) {
standardDpi = 120;
} else if (w < 480) {
standardDpi = 160;
} else if (w < 640) {
standardDpi = 240;
} else if (w < 960) {
standardDpi = 320;
} else if (w < 1280) {
standardDpi = 480;
} else {
standardDpi = 640;
}
}
dpi = 640 * standardDpi / w;
dpi = Math.floor(dpi);
scale = 640 / w;
var userAgt=navigator.userAgent;
if(window.devicePixelRatio === 3 && window.navigator.appVersion.match(/iphone/gi)){
// iphone6 plus
text = '<meta name="viewport" content="width=device-width, initial-scale=0.64, maximum-scale=0.64, minimum-scale=0.64, user-scalable=no" />';
}else if (window.devicePixelRatio === 2 && window.navigator.appVersion.match(/iphone/gi)) {
text = '<meta name="viewport" content="width=device-width, initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no" />';
}else if(userAgt.match(/Firefox/gi)||(userAgt.match(/Chrome/gi) && !userAgt.match(/MicroMessenger/gi))) {
text = '<meta name="viewport" content="width=640,initial-scale='+ (w / 640) +', maximum-scale='+ (w / 640) +', minimum-scale='+ (w / 640) +', user-scalable=no"/>';
} else{
text = '<meta name="viewport" content="width=640,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0,target-densitydpi=' + dpi + ', user-scalable=no"/>';
}
document.write(text);
if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode("@-ms-viewport{width:auto!important}")
);
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}
})();
</script>