js实现相同容器内部不同尺寸图片自适应

需求:多个显示区,宽高等比变化,每个显示区域内的原始图片比例、尺寸不同,让图片比例不失调自适应显示区域。

解决方法:将图片等比例缩放后,只显示图片的部分区域

HTML:row和col-xs-6是bootstrap的栅格类

<div class="row">
    <div class="col-xs-6">
        <a class="wrap" href="">
            <img onload="autoSizeImg(this)" src="" alt="...">
        </a>
    </div>
    <div class="col-xs-6">
        <a class="wrap" href="">
            <img onload="autoSizeImg(this)" src="" alt="...">
        </a>
    </div>
</div>
a.wrap{
    overflow:hidden;
    float:left;
    width:100%;
    height:160px;
}
function autoSizeImg(obj){
    height = $(obj).parent("a").height();
    width = $(obj).parent("a").width();
    if($(obj).width() <= $(obj).height()){
        $(obj).css("width", "100%");
        if($(obj).height() > height){
            $(obj).css("top", "-"+($(obj).height()-height)/2+"px");
        }else{
            var rate = (height-$(obj).height())/height;
            var rateWidth = $(obj).width()*(1+rate);
            $(obj).width(rateWidth);
            $(obj).css("left", "-"+($(obj).width()-width)/2+"px");
            $(obj).css("height", "100%");
        }
    }else{
        $(obj).css("height", "100%");
        if($(obj).width() > width){
            $(obj).css("left", "-"+($(obj).width()-width)/2+"px");
        }else{
            var rate = (width-$(obj).width())/width;
            var rateHeight = $(obj).height()*(1+rate);
            $(obj).height(rateHeight);
            $(obj).css("top", "-"+($(obj).height()-height)/2+"px");
            $(obj).css("width", "100%");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/taian1665/article/details/79099983