一个简单的示例,实现css+js限制一行文本,超限缩小字号。
适用场景:网页底部的版权信息等。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Dynamic Text Size</title>
<style>
.container {
width: 400px; /* 容器宽度 */
white-space: nowrap; /* 防止文本换行 */
/* overflow: hidden; /* 超出部分隐藏
text-overflow: ellipsis; /* 超出部分显示省略号
*/
}
</style>
</head>
<body>
<div class="container" id="textContainer">
这是一段很长的文本,可能会超过容器的宽度,我们希望文本能够自动缩小字体大小以适应一行。
</div>
<script>
const container = document.getElementById("textContainer")
const originalFontSize = parseFloat(getComputedStyle(container).fontSize)
let currentFontSize = originalFontSize
function adjustFontSize() {
container.style.fontSize = currentFontSize + "px"
if (container.scrollWidth > container.clientWidth) {
// 如果内容仍然超出容器宽度,则减小字体大小
currentFontSize -= 1
adjustFontSize()
}
}
// 初始化调整字体大小
adjustFontSize()
</script>
</body>
</html>