<!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>