调整图像大小以保持在视口内

时间:2015-07-16 01:06:42

标签: javascript jquery html css image

如果图像大于容器,如何调整图像大小并保持纵横比保持在容器内,但如果图像小于容器则不调整大小。

如果图像的宽度大于容器的宽度,则应该应用以下代码。

img {
    width: 100%;
    height: auto;
}

如果图像的宽度小于容器的宽度,则应使用以下代码。

img {
    width: auto;
    height: 100%;
}

我尝试使用以下代码,但是当图像宽度大于容器的宽度时会发生一些奇怪的事情。

img_w = parseInt($("#img").css("width"));
screen_w = parseInt($(window).width());

img_w = parseInt($("#img").css("width"));
screen_w = parseInt($(window).width());

if (img_w > screen_w) {
    $("#img").css("width", screen_w + "px"); // like 100%;
    $("#img").css("height", "auto");
} else {
    $("#img").css("width", "auto");
    $("#img").css("height", "100%");
}

2 个答案:

答案 0 :(得分:4)

使用以下CSS解决了问题:

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

答案 1 :(得分:-1)

我尝试了您的代码,您可以在此处看到结果:http://jsfiddle.net/g6rL3L5h/ 我认为它现在可以正常工作。

我只是删除你的CSS中的'html'。

body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    text-align: center;
  }
你需要这个吗?

相关问题