如果文本对于框来说太大(适合框),我有一个算法可以减小给定文本框中的字体大小
它工作得很好,但效率很低,因为它实际上只是将字体大小减小 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>
最佳答案
这是一个将循环计数从示例中的 9 次减少到 4 次的版本:
function fitToBox(box, maxFontSize, minFontSize, maxHeight) {
inc = (maxFontSize - minFontSize) / 2;
currentFontSize = minFontSize + inc;
box.style.fontSize = currentFontSize+"pt";
while(inc >= 1) {
if(box.offsetHeight > maxHeight) {
dir = -1;
} else {
dir = 1;
}
inc = Math.floor(inc/2);
currentFontSize += (dir * inc);
box.style.fontSize = currentFontSize+"pt";
}
}
它首先假设中间尺寸是一个好的开始,然后二进制文件将其方式切向低于最大值的最佳拟合,并根据需要改变方向。
我不明白为什么你要改变 CSS 行高,所以我没有这样做。
关于javascript 调整字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13609853/