<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文字自动填充容器</title>
<style>
body {
display: flex;
}
textarea {
width: 200px;
height: 200px;
margin-left: 20px;
}
.outer {
width: 200px;
height: 200px;
box-sizing: border-box;
border: 1px solid #F56C6C;
}
.container {
word-wrap: break-word;
word-break: break-all;
white-space: break-spaces;
box-sizing: border-box;
border: 1px dashed #67C23A;
}
</style>
</head>
<body>
<div class="outer">
<div class="container">这是一段很长的文本内容,当内容超出容器宽度时,字体大小会自动缩小来适应容器。</div>
</div>
<textarea oninput="input(this.value)"></textarea>
</body>
<script>
let findFontSize = (container, { text, fontSize = 100, containerHeight = 100 } = {}) => {
container.innerText = text;
let setFontSize = (size) => (container.style.fontSize = `${size}px`);
setFontSize(fontSize);
// 如果内容超过了容器高度就减小字号
console.log(``, container.offsetHeight);
while (container.offsetHeight > containerHeight) {
fontSize--, setFontSize(fontSize);
}
}
let input = (text) => findFontSize(document.querySelector(`.container`), { text, containerHeight: 200 });
</script>
</html>