前言
因为移动端屏幕尺寸大小不一,前端开发的时候,往往根据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