萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 批次限制文章內圖片最大寬度 (等比縮放)

核心函式

function limitImgMaxWidth(container, maxW) {
  $(container).find('img').each(function () {
    var $img = $(this), w = $img.width(), h = $img.height();
    if (w > maxW) {
      var ratio = maxW / w;
      $img.css({ width: maxW, height: h * ratio });
    }
  });
}

// 使用
$(function () { limitImgMaxWidth('.news-content', 634); });

完整範例

<div class="news-content">
  <img src="large.jpg" width="1200" height="800" />
  <img src="small.jpg" width="300" height="200" />
</div>

<script src="jquery.min.js"></script>
<script>
$(function () {
  $('.news-content img').each(function () {
    var maxW = 634, $img = $(this), w = $img.width(), h = $img.height();
    if (w > maxW) $img.css({ width: maxW, height: h * (maxW / w) });
  });
});
</script>

進階:支援 max-height、延遲載入後執行

function resizeImages(container, maxW, maxH) {
  $(container).find('img').on('load', function () {
    var $img = $(this), w = $img.width(), h = $img.height();
    var ratio = Math.min(maxW / w, maxH / h, 1);
    if (ratio < 1) $img.css({ width: w * ratio, height: h * ratio });
  }).each(function () { if (this.complete) $(this).trigger('load'); });
}

CSS 替代方案 (零 JS)

.news-content img { max-width: 100%; height: auto; display: block; }

現代專案優先用 CSS `max-width:100%`,JS 僅用於舊版瀏覽器相容或需精確控制高度時。

copyright © 萬盛學電腦網 all rights reserved