CSS/Javascript 图片尺寸调整以适应裁剪并保持纵横比的问题

4
我有一个大小为180x270的块,需要展示图片。
图片尺寸可能会有所不同,我想确保它可以扩展或缩小,以使较小的边框(高度或宽度)与块匹配,而较大的边框则被裁剪,同时保留纵横比。
例如: - 一张360x600的图片被调整大小为180x300,我将高度从300剪裁到270 - 一张100x135的图片被调整大小为200x270,我将宽度从200剪裁到180
基本上,当我扩展/缩小图像时,我想要确保没有白色空间,同时通过裁剪超出块范围的部分来保持长宽比。
是否有任何关于css或javascript可以处理这种情况的建议?
2个回答

3

看起来你正在寻找background-size:cover,这个属性适用于background-image的图片。

background:url(imgurl.jpg) /* Other background image properties */;
background-size:cover;

演示

(Demo)

2
如果您需要使用<img>标签(有时建议这样做),则Zach的解决方案最好,但是您需要使用JavaScript来计算图像的纵横比,并确定它是比目标框更矮胖还是更垂直拉伸。然后还需要一些CSS:

JavaScript

//obtain a dom-reference for the image using getElementById
//or by some other means depending on what you know of its HTML
var img = document.getElementById('some-image-id') 


var aspectRatio = img.clientWidth/img.clientHeight;

//if the img is more squat, set it's height equal to the target frame's height
if(aspectRatio > (270/180)){
    img.style.height = 180 //image is
}
//otherwise the image is more vertically stretched
// so set the img width equal to the target frame's width
else{
    img.style.width = 270;
}

这将设置CSS。最后,为了在包装器内垂直和水平居中一个超大的图像,无论如何进行适配:
.wrapper{
    position:relative;
    display:inline-block; 
}
.wrapper img{
    position:absolute;
    top:-9999px;
    right:-9999px;
    bottom:-9999px;
    left:-9999px;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接