css图片根据div宽高比例自适应
1.div布局
<div class="card-img-show"> <div class="upload-img-conss" > <img style="width: 200px" class="addPersonFile" id="personImg" :src="personImgDataUrl" > <div class="upload-img-success-bg"> <div class="upload-promise-img-chuan-margin"> </div> <p class="upload-img-add-front" style="margin-top: 11px; padding-left: 0">证件有效信息面</p> </div> </div> <div class="card-img-show"> <input style="position: absolute; width: 52%; height: 73%" class="register-person-260-upload" :class="{'is-danger': errors.has('cardImg') }" v-validate="'required|unitCardImg'" name="cardImg" type="file" id="addPersonFile" v-on:change="getFile($event)" placeholder="请上传证件照"> <p v-show="errors.has('cardImg')" style="display:none;color: red;font-size: 12px;">{{ errors.first('cardImg') }}</p> <p class="card-img-show-p">文件格式为:jpg或png;文件大小:1M至5M</p> </div> </div>
效果图
根据图片原始尺寸等比缩放,不拉伸图片宽高;
前端使用vue框架:图片上传完成后渲染
updated(){ $(".register-container img").each(function(){ if(!!$(this).attr("src") && $(this).attr("src").indexOf("http")>-1){ var imgid= $(this).attr("id")
//添加遮罩可忽略 $("#"+imgid+"+ div:first").addClass("upload-img-success-bg-change"); //图片id
var img = $(this); //图片自适应宽高 imgSuite(imgid,img); } }); },
公共js方法
function imgSuite(imgid,img) { var realWidth;//真实的宽度 var realHeight;//真实的高度
//虚拟img标签 $("<img/>").attr("src", $(img).attr("src")).on('load',function() { realWidth = this.width; realHeight = this.height; var upPercent = realWidth/realHeight; var parentDiv = $("#"+imgid).parent(); var parentWidth = parentDiv.width();//父级宽 var parentHeight = parentDiv.height();//父级高 var orgPercent = parentWidth/parentHeight; if(upPercent<orgPercent){ $("#"+imgid).css({width:"auto",height:parentHeight+"px",margin:"0 auto",display:"block"}); }else { var differHeight = parentWidth*realHeight/realWidth;//父级高度减去图片高度差 var marginTop = (parentHeight - differHeight)/2;//距离顶部高 $("#"+imgid).css({height:"auto",width:parentWidth+"px",marginTop: marginTop + "px",display:"block"}); } }); }