html5图片填充距,html5 - 用裁剪后的图像填充div,保留长宽比 - 堆栈内存溢出

我的页面上有包含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,然后在调整大小后显示它们。

这适用于所有容器宽度和图像模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值