如果文本对于框来说太大(适合框),我有一个算法可以减小给定文本框中的字体大小
它工作得很好,但它确实效率低下,因为它实际上只是将字体大小减小了 1 直到它适合。
任何人都可以帮助我提高效率,例如二进制切碎或其他东西吗?
代码是:
function fitToBox(object, maxFontSize, minFontSize, maxHeight) {
var box = document.getElementById(object);
var currentHeight = box.offsetHeight;
var currentFontSize = maxFontSize;
do {
box.style.fontSize = currentFontSize+"pt";
currentFontSize = box.style.fontSize.replace("pt", "");
currentHeight = box.offsetHeight;
if(currentHeight >= maxHeight) {
currentFontSize -= 1;
}
} while (currentHeight > maxHeight && currentFontSize > minFontSize);
box.style.lineHeight = currentFontSize+"pt";
}
HTML 中的完整示例(只需向 div 添加更多文本以查看正在进行的拟合)
<html>
<head>
<script type="text/javascript">
function fitToBox(object, maxFontSize, minFontSize, maxHeight) {
var box = document.getElementById(object);
var currentHeight = box.offsetHeight;
var currentFontSize = maxFontSize;
do {
box.style.fontSize = currentFontSize+"pt";
currentFontSize = box.style.fontSize.replace("pt", "");
currentHeight = box.offsetHeight;
if(currentHeight >= maxHeight) {
currentFontSize -= 1;
}
} while (currentHeight > maxHeight && currentFontSize > minFontSize);
box.style.lineHeight = currentFontSize+"pt";
}
</script>
</head>
<body>
<div id="fitme" style="background-color: yellow; font-size: 24pt; width: 400px;">
This is some text that is fit into the box This is some text that is fit into the box This is some text that is fit into the box
</div>
<script type="text/javascript">
fitToBox("fitme", 24, 4, 80);
</script>
</body>
</html>