//調整多張圖片,讓圖片水平垂直居中圖片
function adjustImg(){get
let imgDiv = document.getElementsByClassName("img");//找到img標籤外面的class 名爲img的div盒子io
for (let i = 0; i < imgDiv.length; i++){console
// console.log(i);function
let obj = imgDiv[i].getElementsByTagName("img")[0];class
if (obj.complete) {//確保圖片已經加載完成im
let imgH = obj.offsetHeight;margin
let imgW = obj.offsetWidth;img
let img_scale = imgW/imgH;di
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";
}
}
}