引入:页面开头处引入下面这段代码,或者放到js里,引入即可用于动态计算font-size
<script type="text/javascript">
(function(doc, win) {
var docEl = doc.documentElement,
isIOS = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
dpr = isIOS ? Math.min(win.devicePixelRatio, 3) : 1,
dpr = window.top === window.self ? dpr : 1, //被iframe引用时,禁止缩放
dpr = 1,
scale = 1 / dpr,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
docEl.dataset.dpr = dpr;
var metaEl = doc.createElement('meta');
metaEl.name = 'viewport';
metaEl.content = 'initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale;
docEl.firstElementChild.appendChild(metaEl);
var recalc = function() {
var width = docEl.clientWidth;
if (width / dpr > 750) {
width = 750 * dpr;
}
// 乘以100,px : rem = 100 : 1
docEl.style.fontSize = 100 * (width / 750) + 'px';
};
recalc()
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
})(document, window);
</script>
在vue中使用的方法
(function (doc, win) {
var docEl = doc.documentElement
var isIOS = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
var dpr = isIOS ? Math.min(win.devicePixelRatio, 3) : 1
var scale = 1 / dpr
var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
docEl.dataset.dpr = dpr
var metaEl = doc.createElement('meta')
metaEl.name = 'viewport'
metaEl.content = 'initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale
docEl.firstElementChild.appendChild(metaEl)
var recalc = function () {
var width = docEl.clientWidth
if (width / dpr > 750) {
width = 750 * dpr
}
docEl.style.fontSize = 100 * (width / 750) + 'px'
}
recalc()
if (!doc.addEventListener) return
win.addEventListener(resizeEvt, recalc, false)
})(document, window)
简单粗暴的网易适配 统统除以100,单位换成rem
使用:未引入前
body {
width: 750px;
height: 640px;
font-size: 20px;
}
引入后:除以100并将px换成rem
@media screen and (max-width: 750px) {
body {
width: 7.5rem;
height: 6.4rem;
font-size: 0.2rem;
}