1. 程式人生 > >前端移動開發螢幕自適應的最好辦法

前端移動開發螢幕自適應的最好辦法

前言

因為移動端螢幕尺寸大小不一,前端開發的時候,往往根據psd大估摸的進行開發,利用百分比進行相容

這樣做出來的頁面和psd可能非常不一樣,且開發緩慢

 

目的

1、開發者只需要量取psd的尺寸直接寫到css中,無需考慮螢幕相容

2、系統根據螢幕大小自動生成相應的css尺寸,小屏自動縮放,大屏自動放大,完全和psd相同

 

解決方案

我們在寫css的時候在相關尺寸的地方換一種方式來寫,暫定

width:/*{1000}*/;

 

然後通過正則把他換一下,程式碼

css = css.replace(new RegExp("\\/\\*real\\{([\\-\\d]+)\\}\\*\\/", "g"),function(all,v){
            return getRealPx(parseInt(v))+'px';
        }.bind(this));

function getRealPx(px){
        //psdWidth是psd的寬度
        return  Math.round(screen.availWidth/psdWidth*px);
}

然後在引用css的地方,我們通過ajax將程式碼引入,通過style標籤加入頁面,完整程式碼

var ScreenAdJust = {
    _loadingCss:false,
    _loadingIndex:-1,
    _cssList:[],
    psdWidth:1080,
    setPsdWidth:function(width){
        this.psdWidth = width;
    },
    addCss:function(css) {
        this._cssList.push(css);
        this._loadCss();
    },
    _loadCss:function(){
        if(!this._loadingCss) {
            if((this._cssList.length-1)>this._loadingIndex) {
                this._loadingCss = true;
                this._loadCssContent(this._cssList[this._loadingIndex+1],function(content){
                    $('<style>'+content+'</style>').appendTo($(document.head));
                    this._loadingIndex ++ ;
                    this._loadingCss = false;

                    this._loadCss();
                }.bind(this))
            }
        }
    },
    _formatCss:function(content){
        html = html.replace(new RegExp("\\/\\*real\\{([\\-\\d]+)\\}\\*\\/", "g"),function(all,v){
            return this.getRealPx(parseInt(v))+'px';
        }.bind(this));
    },
    getRealPx : function(px){
        return  Math.round(screen.availWidth/this.psdWidth*px);
    },
    _loadCssContent:function(css,complete){
        this.getCssContent(css,complete);
    },
    //跨域的情況,請重寫這個方法
    getCssContent:function(css,complete) {
        //這裡可能產生跨域問題,特別是帶cdn的情況,可以採取
        $.get(css,function(content){
            complete(content);
        })
    }
};

我們以前在head中引入css的程式碼需要修改

<head>
 <link rel="stylesheet" rev="stylesheet" href="style.css" type="text/css"/>
</head>

<!--修改為一下程式碼-->

<head>
<!--引入js-->
<script src="adjust.js"></script>
<script>
ScreenAdJust.addCss("style.css")
</script>
</head>

執行一下完美解決問題

執行例項和程式碼

https://github.com/suxianbaozi/mobilescreen