天天看點

移動端rem布局的實作

js實作rem布局

支援移動端和pc端的H5頁面,直接上代碼

!(function(win, doc) {
            function setFontSize() {
                var winWidth = window.innerWidth;
                doc.documentElement.style.fontSize = (winWidth / 750) * 100 + 'px';
                // 移動端一般是750,以設計稿的寬度為準
            }
            var evt = 'onorientationchange' in win ? 'orientationchange' : 'resize';
            var timer = null;
            win.addEventListener(evt, function() {
                clearTimeout(timer);
                timer = setTimeout(setFontSize, 300);
            }, false);
            win.addEventListener("pageshow", function(e) {
                if (e.persisted) {
                    clearTimeout(timer);
                    timer = setTimeout(setFontSize, 300);
                }
            }, false);
            //初始化 
            setFontSize();
        }(window, document));
           

然後H5頁面裡的寬和高就以本身寬高的1%,例如一個div的寬度為200px,就寫成2rem即可。

繼續閱讀