如何利用rem在移动端不同设备上让字体自适应大小

function page() {
//通过navigator判断是否是移动设备
    if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
//在移动端
        (function (doc, win) {
            //  html
            var docEl = doc.documentElement,
                resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function () {
                    var clientWidth = docEl.clientWidth;
                    if (!clientWidth) return;
                    clientWidth = (clientWidth > 768 ) ? 768 : clientWidth ; docEl.style.fontSize = 10 * (clientWidth / 375 ) + 'px';      //这个10可以根据自己使用的数据来调整
                };
            if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false);
            recalc();
        })(document, window);
//移动端  文字适配
    }
    else {       //如果是pc端我们可以像微信公众号那样,设置最大宽度为740px
//      window.location.href="prompt.html"
         document.documentElement.style.maxWidth=740+'px';
         document.documentElement.style.margin="0 auto"
//PC端
    }}
page();

html{font-size:62.5%}

body{font-size:1.2rem}

使用时建议单独建一个js包,要用直接引用就行,引入上面 的js代码后(注意:将js包在页面加载前边引入),字体高度使用rem作为单位,宽带设为百分比,项目在不同的移动端设备就会自动适应屏幕啦

转载:http://www.cnblogs.com/lamb97/p/6096452.html

原文地址:https://www.cnblogs.com/xiaomili/p/6780275.html