<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
.a {
width: 100%;
height: 100%;
background: skyblue;
position: relative;
}
.b {
background: deeppink;
position: absolute;
}
</style>
</head>
<body>
<div class="a box" id="box">
<div class="b"></div>
</div>
<script>
// 容器计算内容框 w , h , top , left
function getFrameSize(container, frame) {
// 父盒子宽高
const { width, height } = container.getBoundingClientRect();
// 子盒子宽高比
const radio = 1.25
// 父盒子宽高比
const containerRa = width / height
let w, h, topback, leftback
if (containerRa > radio) {
h = height
w = height * radio
topback = (height - h) / 2
leftback = (width - w) / 2
} else {
w = width
h = width / radio
topback = (height - h) / 2
leftback = (width - w) / 2
}
return {
w,
h,
topback,
leftback
}
}
// 获取元素并显示尺寸信息
function showBoxDimensions() {
const box = document.getElementById('box');
const frame = document.querySelector('.b');
const { w, h, topback, leftback } = getFrameSize(box, frame)
frame.style.cssText = `
width: ${w}px;
height: ${h}px;
left: ${leftback}px;
top: ${topback}px;
`;
// frame.setAttribute('style', `
// width: ${w}px;
// height: ${h}px;
// left: ${leftback}px;
// top: ${topback}px;
// `);
}
// 在窗口大小改变时重新获取尺寸
window.addEventListener('resize', showBoxDimensions);
// 初始获取
showBoxDimensions();
</script>
</body>
</html>