javascript 调整字体大小

标签 javascript

如果文本对于框来说太大(适合框),我有一个算法可以减小给定文本框中的字体大小

它工作得很好,但效率很低,因为它实际上只是将字体大小减小 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/

相关文章:

javascript - AngularJS 中的 CORS 错误

javascript - 如何将使用 "this"关键字的函数传递到 JavaScript 类中?

javascript - 如何使用单选按钮获取选定的icefaces数据表行?

javascript - MVC SPA + knockout

javascript - Promise 返回 undefined

javascript - 如何使用文件系统和nodejs从文件中获取匹配的字符串?

php - 避免使用相同的用户名和密码多次登录

javascript - 警告 : setState(. ..):在 React Redux 中现有状态转换期间无法更新

javascript - 页面内容仅在硬刷新后显示,不在重定向时显示

JavaScript初学者,如果一个变量不匹配做某事