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>
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'); });
}
.news-content img { max-width: 100%; height: auto; display: block; }
現代專案優先用 CSS `max-width:100%`,JS 僅用於舊版瀏覽器相容或需精確控制高度時。