直接上代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.box{
width: 300px;
height: 400px;
margin: 50px 50px;
position: relative;
/* overflow: hidden; */
}
.show{
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
border: 1px solid red;
position: absolute;
left: 0;
top: 0;
z-index: 999;
color: #FFF;
text-align: center;
line-height: 400px;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="box">
<div class="show">顯示區(qū)域</div>
<img class="img" src="img/5.png" />
</div>
<div class="box" style="overflow: hidden;">
<img class="img" src="img/5.png" />
</div>
<script>
var box = document.getElementsByClassName("box")[0]; // box
var img = document.getElementsByClassName("img")[0]; // img
var img1 = document.getElementsByClassName("img")[1]; // img
// 計(jì)算后的圖寬,高, 定位:左是己,上
var count_width,
count_height,
cont_left = 0,
cont_top = 0;
// 獲取圖片地址汛兜,圖片的數(shù)據(jù)都沒有被加載前它的寬高默認(rèn)就是0颠焦, 需要用onload事件獲取圖片數(shù)據(jù)
img.onload = function(){
// 獲取圖片寬高
let img_width = img.width,
img_height = img.height;
let img_ratio = img_width / img_height; // 計(jì)算圖片寬高比
console.log("圖w:"+img_width, "圖h:"+img_height, "圖寬高比:"+img_ratio);
// 獲取盒子寬高
let box_width = box.clientWidth,
box_height = box.clientHeight;
let box_ratio = box_width / box_height; // 計(jì)算盒子寬高比
console.log("盒w:"+box_width, "盒h:"+box_height, "盒寬高比:"+box_ratio);
// 圖片比例大于盒子比例, 等比縮放左右居中
if( img_ratio > box_ratio ) {
count_height = box_height; // 計(jì)算圖h = 盒h
count_width = box_height * img_ratio; // 計(jì)算圖w = 盒h * 圖寬高比
cont_left = -((count_width/2)-(box_width/2)); // 計(jì)算圖居中定位 = -((計(jì)算后圖w/2)-(盒w/2))
// 圖片比例小于盒子比例
}else if ( img_ratio < box_ratio ) {
// 判斷圖寬小于盒寬就等比縮放上下居中,否則等比縮放左右居中
if( img_width < box_width ){
// 上下居中
count_height = img_height * box_width / img_width; // 計(jì)算圖h = 圖h * 盒w / 圖w
count_width = box_width; // 計(jì)算圖w = 盒w
cont_top = -((count_height/2)-(box_height/2)); // 計(jì)算圖居中定位 = -((計(jì)算后圖w/2)-(盒w/2))
}else{
// 左右居中
count_height = box_height; // 計(jì)算圖h = 盒h
count_width = box_height * img_ratio; // 計(jì)算圖w = 盒h * 圖寬高比
cont_left = (box_width/2) - (count_width/2) // 計(jì)算圖居中定位 = (計(jì)算后圖w/2)-(盒w/2)
}
}
// 設(shè)置圖片寬高里逆,定位
img.style.cssText = `
width:${count_width}px;
height:${count_height}px;
position:absolute;
top: ${cont_top}px;
left: ${cont_left}px;`;
img1.style.cssText = `
width:${count_width}px;
height:${count_height}px;
position:absolute;
top: ${cont_top}px;
left: ${cont_left}px;`;
}
</script>
</body>
</html>
效果圖:
圖片比例大于盒子比例, 等比縮放左右居中
圖片寬高比大于盒子寬高比.png
圖片比例小于盒子比例, 等比縮放上下居中
上下居中.png
圖片比例小于盒子比例, 等比縮放左右居中
左右居中.png