DIV CSS 佈局教程網

讓指定區域內的圖片自動按比例縮小
編輯:JavaScript綜合知識     

後台編輯的文章常常貼進原始尺寸的大圖,結果版面被撐破或看不全。CSS 的 max-width 可以處理,但受限於舊瀏覽器與圖片本身帶有 width、height 屬性的情況,用 JS 補一層會更穩。

做法一:逐一檢查寬高再等比縮放

<div id="article">
  <img height="800" width="1280" src="/down/js/images/12498880470.jpg" alt="" />
</div>
<script type="text/javascript">
function ResizeImages() {
  var myimg, oldwidth, oldheight;
  var maxwidth = 550, maxheight = 880;
  var imgs = document.getElementById('article').getElementsByTagName('img');

  for (var i = 0; i < imgs.length; i++) {
    myimg = imgs[i];
    if (myimg.width > myimg.height) {          // 橫式圖看寬度
      if (myimg.width > maxwidth) {
        oldwidth = myimg.width;
        myimg.height = myimg.height * (maxwidth / oldwidth);
        myimg.width = maxwidth;
      }
    } else {                                    // 直式圖看高度
      if (myimg.height > maxheight) {
        oldheight = myimg.height;
        myimg.width = myimg.width * (maxheight / oldheight);
        myimg.height = maxheight;
      }
    }
  }
}
ResizeImages();
</script>

核心觀念只有一個:先把被動的那一邊乘上縮放比例,再限制主動的那一邊,比例才不會跑掉。若你的容器 id 不叫 article,記得改掉 getElementById 的字串。這裡的判斷是「寬 > 高」看寬、否則看高,對接近正方形的圖會偏向以高為準,實務上可改成「超出哪個上限就縮哪邊」。

做法二:更通用的 controlImg

function controlImg(ele, w, h) {
  var c = ele.getElementsByTagName("img");
  for (var i = 0; i < c.length; i++) {
    var w0 = c[i].clientWidth, h0 = c[i].clientHeight;
    var t1 = w0 / w, t2 = h0 / h;             // 各自的放大倍率
    if (t1 > 1 || t2 > 1 || w0 >= 600) {
      var ratio = (t1 > t2 ? t1 : t2);        // 取較大的倍率
      c[i].width  = Math.floor(w0 / ratio);
      c[i].height = Math.floor(h0 / ratio);

      if (document.all) {                     // 舊 IE:包一層連結
        c[i].outerHTML = '<a href="' + c[i].src + '" target="_blank"'
                       + ' title="在新窗口查看圖片">' + c[i].outerHTML + '</a>';
      } else {
        c[i].title = "在新窗口打開圖片";
        c[i].onclick = function () { window.open(this.src); };
      }
    }
  }
}

ele 是容器,w 與 h 是允許的最大寬高,超過就縮。這版的優點是「兩個上限同時考慮」,取倍率較大者相除,因此不管圖片偏橫或偏直都不會溢出;縮完之後還順手包上連結,讓使用者能點開看原圖,體貼度更高。

今日的簡便寫法

#article img { max-width: 100%; height: auto; }

max-width 加 height: auto 已是公認的響應式圖片標準寫法,一行取代上面數十行,且不會造成版面抖動(版面在圖片載入後才重排)。JS 方案在需要「縮完就連原圖連結一起產生」或要支援不認得 max-width 的舊環境時仍有價值,但如果是新專案,請直接用 CSS。

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