DIV CSS 佈局教程網

移動Web中圖片自適應的兩種JavaScript方案
編輯:JavaScript綜合知識     

本文主要講解移動Web中如何讓圖片根據手機屏幕大小自適應居中顯示,並針對兩種常見場景給出解決方案。

在製作配合手機客戶端的Web Wap頁面時,發現文章對圖片顯示有兩種特別重要的需求。一是圖集類文章,用戶只需左右滑動瀏覽,最佳體驗是讓圖片縮放後完整顯示在屏幕可視範圍內,避免圖片過大導致用戶得滑動手指移動圖片才能看全,那樣體驗會大打折扣。二是圖文混排的文章,圖片最大寬度不超過屏幕寬度,高度則可auto。這兩種情況在項目中很常見。有人建議做個圖片切割工具,把圖片比例統一為相同尺寸,但即便如此,面對各種大小的移動設備屏幕,也無法用單一方案解決所有問題;何況需求一多,服務器上得存多少份不同尺寸的圖片呢?顯示並不現實。

圖集類型:寬高都限制在可視範圍內

需求方要求圖片的高與寬都保持在手機可視視野範圍內,JS代碼如下:

<script type="text/javascript">
$(function(){
  var imglist = document.getElementsByTagName("img");
  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; }\br />          else{ ImgD.width=image.width; ImgD.height=image.height; }
        }
      }
    }
  }
})
</script>

注意:測試中發現安卓4.0+系統對window.screen.width屬性支持不佳,首次加載時返回的屏幕像素常常不正確。本人的安卓2.3.3系統測試通過,支持該屬性。據說這是安卓系統的bug,可以透過setTimeout延時來解決,但本人測試並行不通,於是改用window.innerWidth,未發現兼容問題,效果良好。

圖文並茂類型:僅限制寬度

第二種情況是圖文並茂的文章類型,此時只要求圖片寬度適應手機寬度,對高度不做限制,相對簡單一些。改造後的代碼如下:

<script type="text/javascript">
$(function(){
  var imglist = document.getElementsByTagName("img");
  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(){
      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; }
      }
    }
  }
})
</script>

說明:代碼中的resize函數用來捕捉屏幕窗口變化,始終保證圖片依屏幕寬度合理顯示。當然,前提是像我的項目一樣,文章為富文本格式,圖片的父級標籤已設定text-align:center的居中屬性。如果你的文章內容是直接調用第三方的,那麼可以在上面的JS代碼中補充相應的處理語句即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved