我正在尝试调整响应式全屏图像的大小以适应浏览器窗口,而不会发生任何裁剪。
到目前为止,我的起点是设置 max-width: 100%
在图像上,使其填满页面的宽度。但是,如果窗口的高度发生变化,我需要将其从 max-width: 100%
切换到至 max-height: 100%
所以图像永远不会裁剪。
我能想到的唯一方法是找出哪个方面更大,然后将 CSS 更改为使用 max-width: 100%
或 max-height: 100%
相应地。
这是到目前为止的代码。它在按宽度而不是按高度调整大小时有效:
$(document).on("ready", function() {
resizeImage($("#image"), $(window));
$(window).on("resize", function() {
resizeImage($("#image"), $(window));
});
});
function resizeImage(image, container) {
var widthRatio = Math.min(image.width() / container.width()),
heightRatio = Math.min(image.height() / container.height());
if (heightRatio > widthRatio) {
image.css({
"max-width" : "none",
"max-height" : "100%"
});
}
else {
image.css({
"max-width" : "100%",
"max-height" : "none"
});
}
}
这是标记:
<div class="imageContainer">
<img src="ferrari5.jpg" id="image">
</div>
这是一个 CodePen 示例:
最佳答案
容器是否 max-width: 100%, max-height: 100%?如果不是,您只是将问题从图像转移到了容器。 jsfiddle.net 会有所帮助。
很高兴这有帮助:)
关于javascript - 无需裁剪的响应式全屏图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681811/