如果图像大于容器,我如何调整图像大小并保持宽高比以保持在容器内,但如果图像小于容器,则不调整大小。
如果图像的宽度大于容器的宽度,则应应用以下代码。
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%");
}
最佳答案
使用以下 CSS 解决了问题:
img {
max-width:100%;
max-height:100%;
width: auto;
height: auto;
}
关于javascript - 调整图像大小以保持在视口(viewport)内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31443775/