<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.box{
300px;
height: 400px;
margin: 50px 50px;
position: relative;
/* overflow: hidden; */
}
.show{
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">显示区域</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
// 计算后的图宽,高, 定位:左,上
var count_width,
count_height,
cont_left = 0,
cont_top = 0;
// 获取图片地址,图片的数据都没有被加载前它的宽高默认就是0, 需要用onload事件获取图片数据
img.onload = function(){
// 获取图片宽高
let img_width = img.width,
img_height = img.height;
let img_ratio = img_width / img_height; // 计算图片宽高比
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; // 计算盒子宽高比
console.log("盒w:"+box_width, "盒h:"+box_height, "盒宽高比:"+box_ratio);
// 图片比例大于盒子比例, 等比缩放左右居中
if( img_ratio > box_ratio ) {
count_height = box_height; // 计算图h = 盒h
count_width = box_height * img_ratio; // 计算图w = 盒h * 图宽高比
cont_left = -((count_width/2)-(box_width/2)); // 计算图居中定位 = -((计算后图w/2)-(盒w/2))
// 图片比例小于盒子比例
}else if ( img_ratio < box_ratio ) {
// 判断图宽小于盒宽就等比缩放上下居中,否则等比缩放左右居中
if( img_width < box_width ){
// 上下居中
count_height = img_height * box_width / img_width; // 计算图h = 图h * 盒w / 图w
count_width = box_width; // 计算图w = 盒w
cont_top = -((count_height/2)-(box_height/2)); // 计算图居中定位 = -((计算后图w/2)-(盒w/2))
}else{
// 左右居中
count_height = box_height; // 计算图h = 盒h
count_width = box_height * img_ratio; // 计算图w = 盒h * 图宽高比
cont_left = (box_width/2) - (count_width/2) // 计算图居中定位 = (计算后图w/2)-(盒w/2)
}
}
// 设置图片宽高,定位
img.style.cssText = `
${count_width}px;
height:${count_height}px;
position:absolute;
top: ${cont_top}px;
left: ${cont_left}px;`;
img1.style.cssText = `
${count_width}px;
height:${count_height}px;
position:absolute;
top: ${cont_top}px;
left: ${cont_left}px;`;
}
</script>
</body>
</html>
效果图
图片比例大于盒子比例, 等比缩放左右居中
图片比例小于盒子比例, 等比缩放上下居中
图片比例小于盒子比例, 等比缩放左右居中