<script type="text/javascript">
自定义rem的值,取到屏幕实际宽度/10,window.devicePixelRatio是设备上物理像素
var rem = document.documentElement.clientWidth * window.devicePixelRatio / 10;
重置html的fontsize
document.documentElement.style.fontSize = rem + "px";添加meta标签及其属性;
var e = document.createElement("meta");
e.setAttribute("name","viewport");
e.setAttribute("content","width=" + document.documentElement.clientWidth * window.devicePixelRatio + ",user-scalable=no");
document.head.appendChild(e);
</script>
<div style="width: 5rem; height: 5rem;background: #777;">
</div>
/** | |
* @file: wx-flexible.js V1.0.0; | |
* @author: yy; | |
* @copyright: 基于 lib-flexible.js | MIT License; | |
* @doc: | |
* 1.文档读取时自动执行,没有依赖; | |
* 2.推荐作为第一个加载的js文件; | |
* 3.设定屏幕宽度:重置viewport大小为设备像素*设备dpr; | |
* 4.重置rem:屏幕宽度的十分之一,同时还原body字号为14px; | |
* 5.设置html的dpr属性,以防在某些场景下使用(如:特别设置阅读字体); | |
* 6.理论上,可以在所有移动设备上使用。目前只测试了大部分设备的微信浏览器; | |
**/ | |
~(function() { | |
function setting() { | |
// viewport的宽度设置为视口大小乘以设备dpr,固定初始1倍缩放 | |
var meta = document.createElement("meta"), | |
dpr = window.devicePixelRatio, | |
screenW = window.screen.width* dpr + "px", | |
_time = null; | |
meta.setAttribute("name","viewport"); | |
meta.setAttribute("content","user-scalable=no,width="+ parseFloat(screenW)); | |
document.head.appendChild(meta); | |
// 为html设置一个dpr属性,为以后计算作为参考 | |
document.documentElement.setAttribute('data-dpr', dpr); | |
// 重置rem方法 | |
function refreshRem() { | |
var rem = parseFloat(screenW)/ 10; | |
document.documentElement.style.fontSize= rem + 'px'; | |
} | |
// 监听pageshow,防止存缓存中读取 | |
window.addEventListener('pageshow',function(e) { | |
if (e.persisted) { | |
clearTimeout(_time); | |
_time = setTimeout(refreshRem, 300); | |
} | |
}); | |
// 监听方式,重置body字号 | |
document.addEventListener('DOMContentLoaded',function() { | |
document.body.style.fontSize= 14 + 'px'; | |
}); | |
// 直接调用,保证rem被重置 | |
refreshRem(); | |
} | |
var userAgent = window.navigator.userAgent, | |
isMoblie = (!!userAgent.match(/iphone/i))|| (!!userAgent.match(/ipad/i))|| (!!userAgent.match(/Android/i)); | |
if (!isMoblie) { | |
throw new Error("请在移动端打开!"); | |
} | |
setting(); | |
})(); //直接执行,防止jQuery的ready优先调用出现错误 |