標籤:
在做配合手機用戶端的Web wap頁面時,發現文章對圖片顯示的需求有兩種特別重要的情況,一是對於圖集,這種文章只需要左右滑動瀏覽,最好的體驗是讓圖片縮放顯示在螢幕有效範圍內,防止圖片太大導致使用者需要滑動手指移動圖片來查看這種費力氣的事情,使用者體驗大大降低。二是圖文混排的文章,圖片最大寬度不超過螢幕寬度,高度可以auto。這兩種情況在項目中很常見。另外,有人說做個圖片切割工具,把圖片尺寸比例都設定為統一的大小,但即使這樣,面對各種大小的行動裝置螢幕,也是無法適用一個統一方案就能解決得了的。而且如果需求太多,那伺服器上得存多少份不同尺寸的圖片呢?顯示不太符合實際。
下面是圖集類型,需求方要求圖片高寬都保持在手機可視視野範圍,js代碼列在下面:
$(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代碼,如下:
$(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; } }}} })
移動Web開發圖片自適應兩種常見情況解決方案