我可以根据字母数改变字体大小吗?

时间:2012-12-16 22:15:04

标签: javascript html css frontend

  

可能重复:
  Auto-size dynamic text to fill fixed size container

我有一个显示用户名的框。但是我发现它只能容纳10个字母 - 我使用标准h1字体大小。

有没有办法根据字母数改变font-size?我的用户名范围为3到10个字符。

1 个答案:

答案 0 :(得分:3)

请尝试以下代码。

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">

    $(function() {
        var len_fit = 10; // According to your question, 10 letters can fit in.
        var un = $('#user_name');

        // Get the lenght of user name.
        var len_user_name = un.html().length;
        if(len_fit < len_user_name ){

            // Calculate the new font size.
            var size_now = parseInt(un.css("font-size"));
            var size_new = size_now * len_fit/len_user_name;

            // Set the new font size to the user name.
            un.css("font-size",size_new); 
        }
    });
</script>
</head>
<body>
    <h1 id="user_name">Your Long Name</h1>
</body>

</html>

我希望这可以帮到你。