//调整多张图片,让图片水平垂直居中
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.style.marginLeft = -w + "px";
}
} else {
obj.onload = function(){
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.style.marginLeft = -w + "px";
}
};
// obj.style.height = "100%";
// obj.style.margin = "0 auto";
}
}
}