html5 移动端rem

首先说下rem和em,它们都是相对单位,一般我们使用它们是为了适应各种手机屏幕。rem是根据html的根节点来计算,em是继承父元素的字体。下面是移动的rem函数,其中1rem=100px。

! function(e, t) {
    function n() {
        var n = l.getBoundingClientRect().width;
        t = t || 540, n > t && (n = t);
        var i = 100 * n / e;
        r.innerHTML = "html{font-size:" + i + "px;}"
    }
    var i, d = document,
        o = window,
        l = d.documentElement,
        r = document.createElement("style");
    if(l.firstElementChild) l.firstElementChild.appendChild(r);
    else {
        var a = d.createElement("div");
        a.appendChild(r), d.write(a.innerHTML), a = null
    }
    n(), o.addEventListener("resize", function() {
        clearTimeout(i), i = setTimeout(n, 300)
    }, !1), o.addEventListener("pageshow", function(e) {
        e.persisted && (clearTimeout(i), i = setTimeout(n, 300))
    }, !1), "complete" === d.readyState ? d.body.style.fontSize = "16px" : d.addEventListener("DOMContentLoaded", function(e) {
        d.body.style.fontSize = "16px"
    }, !1)
}(750, 750);

但是这样做之后,IPhone X上是不行的。还要在对应的css文件下,加入以下代码。其中has-topbar 和has-bottombar类添加在html文件的html上即可。

        @media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
    /*增加头部适配层*/
    .has-topbar {
        height: 100%;
        box-sizing: border-box;
        padding-top: 44px;
        &:before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 44px;
            background-color: #000000;
            z-index: 9998;
        }
    }
    /*增加底部适配层*/
    .has-bottombar {
        height: 100%;
        box-sizing: border-box;
        padding-bottom: 34px;
        &:after {
            content: '';
            z-index: 9998;
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 34px;
            background: #f7f7f8;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/yanloveyue/p/9172042.html