自适应rem布局

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>圣诞主题</title>
    <style type="text/css">
    section {
        width: 100%;
        height: 100%;
        background: red;
    }
    .page{
        width: 5rem;
        height: 10rem;
        background: yellow;
        font-size: 0.3rem;
    }
    </style>
</head>

<body>
    <section>
        <div class="page">rem跟着html:font-size变化</div>
    </section>
</body>
<script type="text/javascript">
var docEl = document.documentElement,
    //当设备的方向变化(设备横向持或纵向持)此事件被触发。绑定此事件时,
    //注意现在当浏览器不支持orientationChange事件的时候我们绑定了resize 事件。
    //总来的来就是监听当然窗口的变化,一旦有变化就需要重新设置根字体的值
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
    recalc = function() {
        //设置根字体大小
        docEl.style.fontSize = 20 * (docEl.clientWidth / 320) + 'px';
    };

//绑定浏览器缩放与加载时间
window.addEventListener(resizeEvt, recalc, false);
document.addEventListener('DOMContentLoaded', recalc, false);
</script>

</html>

来自:http://www.imooc.com/code/10547

js动态计算rem


!(function(doc, win) {
    var docEle = doc.documentElement,
        evt = "onorientationchange" in window ? "orientationchange" : "resize",
        fn = function() {
            var width = docEle.clientWidth;
            width && (docEle.style.fontSize = 20 * (width / 320) + "px");
        };
     
    win.addEventListener(evt, fn, false);
    doc.addEventListener("DOMContentLoaded", fn, false);
 
}(document, window));

来自:https://segmentfault.com/a/1190000003690140

posted @ 2016-03-02 10:44 Mr.Leo 阅读(...) 评论(...) 编辑 收藏