H5+JS适配不同分辨率的页面

自己用的,页面的font-size定义为100px,其他像素单位用rem,设计比率满屏是750px,在不同的分辨率下都要求铺满100%

(function (win) {
    var doc = win.document,
            $html = doc.getElementsByTagName('html')[0],
            windowWidth = doc.documentElement && doc.documentElement.clientWidth || doc.body.clientWidth || win.innerWidth;
    $html.style.fontSize = windowWidth * (100/750) + 'px';
})(window);

网上找的方法1

new function (){    
var _self = this;    
_self.width = 650;    
_self.fontSize = 100;    
_self.widthProportion = function(){
var p = (document.body&&document.body.clientWidthdocument.getElementsByTagName("html")[0].offsetWidth)/_self.width;return p>1?1:p<0.5?0.5:p;};    
_self.changePage = function(){        
document.getElementsByTagName("html")[0].setAttribute("style","font-size:"+_self.widthProportion()*_self.fontSize+"px !important");    };    
_self.changePage();    window.addEventListener("resize",function(){_self.changePage();},false);};

网上找的方法2

(function (win) {
    var doc = win.document,
            scale = 16,
            $body = doc.getElementsByTagName('body')[0],
            $html = doc.getElementsByTagName('html')[0],
            windowWidth = doc.documentElement && doc.documentElement.clientWidth || doc.body.clientWidth || win.innerWidth,
            windowHeight = document.documentElement && document.documentElement.clientHeight || documentElement.body.clientHeight || window.innerHeight,
            deviceAgent = navigator.userAgent.toLowerCase();
    alert(windowWidth);
    if (deviceAgent.match(/(iphone|ipod|ipad|android|windows\s*phone|symbianos)/)) {
        try {
            if (window.localStorage && window.localStorage.getItem('scale_greatboy')) {
                scale = window.localStorage.getItem('scale_greatboy');
            } else {
                scale = parseFloat(windowWidth * 16 / 320);
                if (windowHeight > windowWidth) {
                    window.localStorage && window.localStorage.setItem('scale_greatboy', scale);
                }
            }
        } catch (e) {
        }
        if (deviceAgent.match(/android\s*2.3/) && deviceAgent.match(/micromessenger/)) {
            scale = 16;
        }
        $html.style.fontSize = scale + 'px';
        $html.style.display = 'block';
    } else {
        window.onresize = function () {
            windowWidth = doc.documentElement && doc.documentElement.clientWidth || doc.body.clientWidth || win.innerWidth;
            scale = parseFloat(windowWidth * 16 / 320);
            $html.style.fontSize = scale + 'px';
        };
        scale = parseFloat(windowWidth * 16 / 320);
        $html.style.fontSize = scale + 'px';
        $html.style.display = 'block';
    }
    alert($html.style.fontSize);
    $body.style.width = '20rem';
})(window);

你可能感兴趣的:(H5+JS适配不同分辨率的页面)