我在我的页面上有DIV
s,其中包含IMG
s。在图像点击时,它们在灯箱中打开,但在DIV内部,它们应该完全填充DIV,但保留宽高比。用裁剪图像填充div,保留长宽比
这是我到目前为止所取得的成绩,问题在于图像处于纵向模式时纵横比不会保留。
所以我需要的是一个CSS的方法来垂直和水平居中图像,而完全填充包装DIV(当然裁剪图像的溢流份)。
这是可能的,仅限CSS,还是需要JS?浏览器兼容性是IE8和Higer以及所有现代浏览器。
与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);
});
}
的设置不透明度为1,在到底是因为我只想完成调整时,显示的图像,所以我将它们设置为不透明:在CSS中为0,然后在调整大小后显示它们。
这适用于我在所有容器宽度和图像模式。
您可以根据图像的大小添加不同的类吗?不同的水平和不同的垂直? – Lucas 2013-05-10 07:25:40
@Lucas也许这是可能的,确定服务器端是哪种图像模式...如果没有其他方式?! – 2013-05-10 08:15:14
请参阅http://php.net/manual/en/function.getimagesize.php,这可能有所帮助。然后为图像容器创建两个css类,一个用于纵向,一个用于横向。或者使用JS! :) – 2013-05-11 02:57:00