在作配合手機客戶端的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; } } } } })