美文网首页Web 前端开发 读书和影视web前端联盟
移动端rem适配问题,与px以百计算。

移动端rem适配问题,与px以百计算。

作者: 像风一样自由2017 | 来源:发表于2017-12-16 13:46 被阅读49次

    随着移动端的发展,rem的用途越来越广泛,很好的解决了px无法适配移动端的问题。因为rem是以根节点来计算的,在根节点不确定或者有变动的情况下,计算起来异常麻烦。下面的代码很好的解决了这个问题。

    var fontSizes;

    (function(win, doc) {

            win.setFontSize = function() {

            var winWidth = window.screen.availWidth;

            var dpr = window.devicePixelRatio;

            var u = navigator.userAgent;

            if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {

                    doc.documentElement.style.fontSize = (winWidth / 640) * 100 + 'px';

                    fontSizes = (winWidth / 640) * 100;

            } else if(u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1) {

                    doc.documentElement.style.fontSize = (winWidth / 640) * 100 + 'px';

                    fontSizes = (winWidth / 640) * 100;

            } else if(u.indexOf('Windows Phone') > -1) {

                    alert("暂不支持winphone手机");

            } else {

                    fontSizes = 100;

            }

     }

    var evt = 'onorientationchange' in win ? 'orientationchange' : 'resize';

    var timer = null;

    win.addEventListener(evt,  function() {

            clearTimeout(timer);

            timer = setTimeout(setFontSize, 300);

    }, {

            passive: false

    });

    win.addEventListener("pageshow", function(e) {

            if(e.persisted) {

                    clearTimeout(timer);

                    timer = setTimeout(setFontSize, 300);

            }

    }, {

            passive: false

    });

    setFontSize();

    }(window, document));

    例如元素宽100px,高100px,只需要设置为高1rem,宽1rem就可以了。

    相关文章

      网友评论

        本文标题:移动端rem适配问题,与px以百计算。

        本文链接:https://www.haomeiwen.com/subject/cdyswxtx.html