css图片在盒子里居中,让图片在div盒子中水平垂直居中

//调整多张图片,让图片水平垂直居中

function adjustImg(){

let imgDiv = document.getElementsByClassName("img");//找到img标签外面的class 名为img的div盒子

for (let i = 0; i < imgDiv.length; i++){

// console.log(i);

let obj = imgDiv[i].getElementsByTagName("img")[0];

if (obj.complete) {//确保图片已经加载完成

let imgH = obj.offsetHeight;

let imgW = obj.offsetWidth;

let img_scale = imgW/imgH;

let boxH = obj.parentNode.offsetHeight;

let boxW = obj.parentNode.offsetWidth;

let box_scale = boxW / boxH;

// console.log("imgH="+imgH+" imgW="+imgW+" boxH="+boxH+" boxW="+boxW);

if(box_scale > img_scale){

obj.style.width = "100%";

imgH = obj.offsetHeight;

imgW = obj.offsetWidth;

let h = (imgH-boxH)/2;

obj.style.marginTop = -h + "px"; //确保图片垂直居中

}else{

obj.style.height = "100%";

imgH = obj.offsetHeight;

imgW = obj.offsetWidth;

let w = (imgW-boxW)/2;

obj.s

你可能感兴趣的:(css图片在盒子里居中)