移动Web开发图片自适应两种常见状况解决方案

在作配合手机客户端的Web wap页面时,发现文章对图片显示的需求有两种特别重要的状况,一是对于图集,这种文章只须要左右滑动浏览,最好的体验是让图片缩放显示在屏幕有效范围内,防止图片太大致使用户须要滑动手指移动图片来查看这种费力气的事情,用户体验大大下降。二是图文混排的文章,图片最大宽度不超过屏幕宽度,高度能够auto。这两种状况在项目中很常见。另外,有人说作个图片切割工具,把图片尺寸比例都设定为统一的大小,但即便这样,面对各类大小的移动设备屏幕,也是没法适用一个统一方案就能解决得了的。并且若是需求太多,那服务器上得存多少份不一样尺寸的图片呢?显示不太符合实际。javascript


下面是图集类型,需求方要求图片高宽都保持在手机可视视野范围,js代码列在下面:css

$(function(){

var imglist =document.getElementsByTagName("img");
//安卓4.0+等高版本不支持window.screen.width,安卓2.3.3系统支持
/*
var _width = window.screen.width;
var _height = window.screen.height - 20;

var _width = document.body.clientWidth;
var _height = document.body.clientHeight - 20;
*/
var _width, 
	_height;
doDraw();

window.onresize = function(){
	doDraw();
}

function doDraw(){
	_width = window.innerWidth;
	_height = window.innerHeight - 20;
	for( var i = 0, len = imglist.length; i < len; i++){
		DrawImage(imglist[i],_width,_height);
	}
}

function DrawImage(ImgD,_width,_height){ 
	var image=new Image(); 
	image.src=ImgD.src; 
	image.onload = function(){
		if(image.width>30 && image.height>30){ 
	 
			if(image.width/image.height>= _width/_height){ 
				if(image.width>_width){
					ImgD.width=_width; 
					ImgD.height=(image.height*_width)/image.width; 
				}else{ 
					ImgD.width=image.width; 
					ImgD.height=image.height; 
				} 
			}else{ 
				if(image.height>_height){
					ImgD.height=_height; 
					ImgD.width=(image.width*_height)/image.height; 
				}else{ 
					ImgD.width=image.width; 
					ImgD.height=image.height; 
				} 
			}
		}	
	}

}
   
});

注意:测试中发现安卓4.0+的系统对window.screen.width属性支持的很差,不少状况在首次加载时返回的屏幕像素不正确。本人的安卓2.3.3系统测试经过,支持该属性。听说,这是安卓系统的bug,能够经过setTimeout设置延时时间来解决这个问题。不过,这个方法,本人怎么测试都行不通。因此干脆仍是另寻高明吧。发现window.innerWidth能够担此重任,没有发现兼容问题,ok。



下面是,第二种状况,图文并茂的文章类型。这时候只对图片宽度和手机宽度适应有要求,对高度不作限制,相对容易些。
改造上面的javascript代码,以下:java

$(function(){
var imglist =document.getElementsByTagName("img");
//安卓4.0+等高版本不支持window.screen.width,安卓2.3.3系统支持
var _width;
doDraw();

window.onresize = function(){
	//捕捉屏幕窗口变化,始终保证图片根据屏幕宽度合理显示
	doDraw();
}

function doDraw(){
	_width = window.innerWidth;
	for( var i = 0, len = imglist.length; i < len; i++){
		DrawImage(imglist[i],_width);
	}
}

function DrawImage(ImgD,_width){ 
	var image=new Image(); 
	image.src=ImgD.src; 
	image.onload = function(){
		//限制,只对宽高都大于30的图片作显示处理
		if(image.width>30 && image.height>30){ 
			if(image.width>_width){
				ImgD.width=_width; 
				ImgD.height=(image.height*_width)/image.width; 
			}else{ 
				ImgD.width=image.width; 
				ImgD.height=image.height; 
			} 

		}	
	}

}
   
})
相关文章
相关标签/搜索