自动改变html font-size,实现移动端rem适配

移动端采用rem适配非常方便

比如在iphone6尺寸下,将html font-size 设置为 100px,那么写css时,只要将尺寸/100 + rem 即可。

1152050-20180126161749881-45396616.png

在iphone6Plus尺寸下,html font-size会自动调节,兼容多种尺寸的手机

1152050-20180126162420787-1111362643.png

以下是js代码,复制到你的项目中即可使用

(function(win) {
var ratio, scaleValue, renderTime,
    htmlEle = document.documentElement,
    vpMeta = document.querySelector('meta[name="viewport"]');

if (vpMeta) {
    var tempArr = vpMeta.getAttribute("content").match(/initial\-scale=(["']?)([\d\.]+)\1?/);
    if (tempArr) {
        scaleValue = parseFloat(tempArr[2]);
        ratio = parseInt(1 / scaleValue);
    }
} else {
    vpMeta = document.createElement("meta");
    vpMeta.setAttribute("name", "viewport");
    vpMeta.setAttribute("content", "width=device-width, initial-scale=0.5, user-scalable=no, minimal-ui");
    htmlEle.firstElementChild.appendChild(vpMeta);
    ratio = 2;
}

win.addEventListener("resize", function() {
    clearTimeout(renderTime);
    renderTime = setTimeout(initPage, 300);
}, false);

win.addEventListener("pageshow", function(e) {
    if(e.persisted){
        clearTimeout(renderTime);
        renderTime = setTimeout(initPage, 300)
    }
}, false);

if("complete" === document.readyState){
    document.body.style.fontSize = 12 * ratio + "px";
}else{
    document.addEventListener("DOMContentLoaded", function() {
        document.body.style.fontSize = 12 * ratio + "px";
    }, false);
}

initPage();

function initPage() {
    var htmlWidth = htmlEle.getBoundingClientRect().width;
    htmlWidth / ratio > 768 && (htmlWidth = 768 * ratio);
    win.rem = 100 * (htmlWidth / 375);
    htmlEle.style.fontSize = win.rem + "px";
}
})(window);

代码分析

1152050-20180126162321428-972583842.png

如果你设置了meta标签的视口属性,则获取initial-scale缩放比例,如果没设置,则自动添加。

一般initial-scale为1

1152050-20180126163454069-1115263998.png

  • line 2 获取屏幕宽度
  • line 3 如果宽度超过768(ipad平板宽度),则不再进行调节
  • line 4、5 设置rem,我以iphone6宽度375设置的,在该尺寸下,rem=100px,如果是其他尺寸,修改375即可

    (htmlWidth/375)得到的是缩放比例,在IPHONE6下计算时,不用管html的font-size,直接px/100即算出rem

1152050-20180126163756522-321113436.png

  • 当页面改变尺寸,或者初次显示的时候,执行方法
  • persisted是pageshow事件的属性,检测浏览器是否读取缓存,是的话为true

1152050-20180126163954881-435714147.png

当页面渲染完后,设置body html-size,防止使用默认样式的元素出错

转载于:https://www.cnblogs.com/zhangceblogs/p/8360368.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值