方法一:
<script>
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = ‘orientationchange‘ in window ? ‘orientationchange‘ : ‘resize‘,
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
docEl.style.fontSize = 20 * (clientWidth / 320) + ‘px‘;
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener(‘DOMContentLoaded‘, recalc, false);
})(document, window);
</script>
方法二:
!function(win, option) {
var count = 0,
designWidth = option.designWidth,
designHeight = option.designHeight || 0,
designFontSize = option.designFontSize || 20,
callback = option.callback || null,
root = document.documentElement,
body = document.body,
rootWidth, newSize, t, self;
root.style.width = 100%;
//返回root元素字体计算结果
function _getNewFontSize() {
var scale = designHeight !== 0 ? Math.min(win.innerWidth / designWidth, win.innerHeight / designHeight) : win.innerWidth / designWidth;
return parseInt( scale * 10000 * designFontSize ) / 10000;
}
!function () {
rootWidth = root.getBoundingClientRect().width;
self = self ? self : arguments.callee;
//如果此时屏幕宽度不准确,就尝试再次获取分辨率,只尝试20次,否则使用win.innerWidth计算
if( rootWidth !== win.innerWidth && count < 20 ) {
win.setTimeout(function () {
count++;
self();
}, 0);
} else {
newSize = _getNewFontSize();
//如果css已经兼容当前分辨率就不管了
if( newSize + ‘px‘ !== getComputedStyle(root)[‘font-size‘] ) {
root.style.fontSize = newSize + "px";
return callback && callback(newSize);
};
};
}();
//横竖屏切换的时候改变fontSize,根据需要选择使用
win.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
clearTimeout(t);
t = setTimeout(function () {
self();
}, 300);
}, false);
}(window, {
designWidth: 640,
designHeight: 1136,
designFontSize: 20,
callback: function (argument) {
console.timeEnd("test")
}
});
方法三:
var dpr, rem, scale;
var docEl = document.documentElement;
var fontEl = document.createElement(‘style‘);
var metaEl = document.querySelector(‘meta[name="viewport"]‘);
scale = 1 / dpr;
dpr = win.devicePixelRatio || 1;
rem = docEl.clientWidth * dpr / 10;
// 设置viewport,进行缩放,达到高清效果
metaEl.setAttribute(‘content‘, ‘width=‘ + dpr * docEl.clientWidth + ‘,
initial-scale=‘ + scale + ‘,maximum-scale=‘ + scale + ‘,
minimum-scale=‘ + scale + ‘,user-scalable=no‘);
// 设置data-dpr属性,留作的css hack之用
docEl.setAttribute(‘data-dpr‘, dpr);
// 动态写入样式
docEl.firstElementChild.appendChild(fontEl);
fontEl.innerHTML = ‘html{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://www.cnblogs.com/luoguixin/p/6403780.html