方案一
fnResize()
window.onresize = function () {
fnResize()
}
function fnResize() {
var deviceWidth = document.documentElement.clientWidth || window.innerWidth
// console.log(deviceWidth)
if (deviceWidth >= 750) {
deviceWidth = 750
}
if (deviceWidth <= 320) {
deviceWidth = 320
}
// 设计稿 750*1334 适配方案 (应用尺寸: 1rem = 100px)
// 由于根节点fontsize转化成rem后会四舍五入,采用1:100的比例能尽可能减小误差,比例越小,偏差越大
document.documentElement.style.fontSize = (deviceWidth / 7.5) + 'px'
}
方案二(添加了微信字体兼容,更全面)
!function (window) {
/* 设计图文档宽度 */
var docWidth = 750;
var doc = window.document,
docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
var recalc = (function refreshRem () {
/* 窗口当前宽度 */
var clientWidth = window.innerWidth;
/* 页面宽度大于 设计图文档宽度 时不再放大 */
clientWidth = clientWidth > docWidth ? docWidth : clientWidth;
var oldSize = (clientWidth/docWidth*100) + 'px';
docEl.style.fontSize = oldSize;
/* 获取设置后的字体大小情况 - 因微信设置APP字体大小后会影响该设置 */
var nowSize = window.getComputedStyle(document.getElementsByTagName("html")[0]).fontSize;
var oldSizeValue = parseFloat(oldSize,10);
var nowSizeValue = parseFloat(nowSize,10);
/* 当差值大于1时重新按差比计算出正确的px值 */
if((nowSizeValue - oldSizeValue) > 1 || (nowSizeValue - oldSizeValue) < -1){
var diff = (oldSizeValue / nowSizeValue);
docEl.style.fontSize = (clientWidth/docWidth*100*diff) + 'px';
}
return refreshRem;
})();
/* 添加倍屏标识,安卓为1 */
docEl.setAttribute('data-dpr', window.navigator.appVersion.match(/iphone/gi) ? window.devicePixelRatio : 1);
if (/iP(hone|od|ad)/.test(window.navigator.userAgent)) {
/* 添加IOS标识 */
doc.documentElement.classList.add('ios');
/* IOS8以上给html添加hairline样式,以便特殊处理 */
if (parseInt(window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/)[1], 10) >= 8)
doc.documentElement.classList.add('hairline');
}
if (!doc.addEventListener) return;
window.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
}(window);