我的页面上有包含IMG的DIV 。 单击图像时,它们会在灯箱中打开,但在DIV内部,它们应完全填充DIV,但要保留宽高比。
这是我到目前为止所实现的,问题是当图像处于纵向模式时,宽高比无法保留。
因此,我需要的是一种CSS方法,在完全填充包装的DIV的同时,将图像垂直和水平居中(并且当然会裁剪图像的溢出部分)。
这可能吗,仅CSS,还是需要JS? 浏览器兼容性是IE8和更高版本以及所有现代浏览器。
用JS / JQuery这样解决了它:
function resizeImages(){
$("#container img").each(function() {
var thisHeight = $(this).height();
var thisWidth = $(this).width();
var containerWidth = $(this).parent().width();
var containerHeight = $(this).parent().height();
var diff = 0;
if(thisHeight > thisWidth){
//portrait
$(this).css("width","100%");
thisHeight = $(this).height();
diff = thisHeight - containerHeight;
$(this).css("margin-top",-(diff/2));
}
else if(thisWidth > thisHeight){
//landscape
$(this).css("height","100%");
var thisWidth = $(this).width();
if(thisWidth < containerWidth){
$(this).css("width", containerWidth);
thisWidth = containerWidth;
}
diff = thisWidth - containerWidth;
$(this).css("margin-left",-(diff/2));
}
$(this).css("opacity",1);
});
}
最后将set-opacity设置为1是因为我只想在调整大小后显示图像,因此我在CSS中将它们设置为opacity:0,然后在调整大小后显示它们。
这适用于所有容器宽度和图像模式。