我的收藏的移動端網頁佈局rem解決方案

寫移動端項目時,老是會糾結是用css3 media query 仍是用rem。移動端框架挺多,可是由於項目都比較小,不考慮使用。css

無心在網上找到一個移動端rem佈局的解決方案,經我的實踐,目前未出現什麼大問題,收藏備用。html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>移動端rem佈局</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
    <style>
        .test{
            width: 1rem;
            height: 1rem;
            background-color: #fa5275;
        }
    </style>
</head>
<body>
    <div class="test"></div>
    <p>設置前html的fontsize:16px;</p>
    <p>設置前html的fontsize:16px;</p>

    <script>
        function adapt(designWidth, rem2px){
            var d = window.document.createElement('div');
            d.style.width = '1rem';
            d.style.display = "none";
            var head = window.document.getElementsByTagName('head')[0];
            head.appendChild(d);
            var defaultFontSize = parseFloat(window.getComputedStyle(d, null).getPropertyValue('width'));
            d.remove();
            document.documentElement.style.fontSize = window.innerWidth / designWidth * rem2px / defaultFontSize * 100 + '%';
            var st = document.createElement('style');
            var portrait = "@media screen and (min-width: "+window.innerWidth+"px) {html{font-size:"+ ((window.innerWidth/(designWidth/rem2px)/defaultFontSize)*100) +"%;}}";
            var landscape = "@media screen and (min-width: "+window.innerHeight+"px) {html{font-size:"+ ((window.innerHeight/(designWidth/rem2px)/defaultFontSize)*100) +"%;}}"
            st.innerHTML = portrait + landscape;
            head.appendChild(st);
            return defaultFontSize;
        }
        var defaultFontSize = adapt(640, 100);
    </script>
</body>
</html>
相關文章
相關標籤/搜索