js控制 固定框架内图片 按比例显示 以及 占满框架 居中显示

js控制 固定框架内图片 等比例显示 以及 占满框架 纵横居中显示

通过设置 js函数 fitDiv里面var fit的值就好

function fitDiv (obj) {
    var target_width=$(obj).parents('.holder').innerWidth();
    var target_height=$(obj).parents('.holder').innerHeight();
    var target_factor=parseInt(target_width)/parseInt(target_height);
    var fit=0;//0 填充满整个区域  1 缩放到适应区域
    var img= new Image();
    img.src=$(obj).attr('src');
    var source_width=img.width > 0 ? img.width : target_width;
    var source_height=img.height > 0 ? img.height : target_height;
    var source_factor=parseInt(source_width)/parseInt(source_height);
    var tmp=0;
    if (source_factor>=target_factor) {
        //原图比较扁平
        //$(obj).css('padding-top',tmp+'px');
            if(fit==1){
                source_height=target_width/source_factor;
                tmp=Math.abs((source_height-target_height)/2);
                $(obj).width(target_width).height(source_height).wrap('<div style="margin-top:'+tmp+'px;"></div>');
            }else{
                source_width=target_height*source_factor;
                tmp=Math.abs((source_width-target_width)/2);
                $(obj).width(source_width).height(target_height).wrap('<div style="margin-left:-'+tmp+'px;"></div>');
            }
    }else{
        //原图比较长条
            if(fit==1){
                tmp=Math.abs((target_width-(target_height*source_factor))/2);
                $(obj).width('auto').height(target_height).wrap('<div style="margin-left:'+tmp+'px;"></div>');
            }else{
                tmp=Math.abs((target_height-(target_width/source_factor))/2);
                $(obj).width(target_width).wrap('<div style="margin-top:-'+tmp+'px;"></div>');
            }
    }
}

window.onload = function(){
        $('.fitfather div img').each(function(){
                fitDiv(this);
        });
}

案例在: http://runjs.cn/code/psh7sjbo

原文地址:https://www.cnblogs.com/lola/p/5771965.html