如果您愿意使用 JQuery(或常规 JavaScript),那么这样的解决方案可能会奏效:
<script>
// Note: this uses jQuery.
// It makes getting/setting the dimensions easier,
// but you can do this with normal JavaScript
var img = $("#img");
var container = $("#container");
var width = img.width();
var height = img.height();
var maxWidth = container.width();
var maxHeight = container.height();
var ratio = maxWidth / width;
if(height * ratio > maxHeight) {
ratio = maxHeight / height;
}
img.width(width * ratio);
img.height(height * ratio);
</script>
Run Code Online (Sandbox Code Playgroud)
它的作用是找到乘以宽度和高度的比率,以较小者为准(以便它始终适合窗口)。
更新:在 JSFiddle.net 上测试。在这里看到它。
我希望这可以帮助你!