【问题标题】:Angular.js: How to reduce font size dynamically based on characters' length?Angular.js:如何根据字符长度动态减小字体大小?
【发布时间】:2016-09-17 11:29:35
【问题描述】:

我正在使用以下代码动态显示名称:

<div id="name">{{profile.name}}</div>

屏幕尺寸始终为 320 像素 如果名称很短,它可以正常工作,但如果名称很长,那么名称会分成两行,这会干扰我的布局。因此,如果名称变得太长,我想自动减小字体大小...

那么有什么方法可以查看 div 的内容并根据字符长度动态应用不同的字体大小?

【问题讨论】:

  • 而不是更改字体大小,您可以尝试使用 css 省略号并将值作为标题。所以它会在元素悬停时显示。

标签: javascript jquery css angularjs


【解决方案1】:

根据您希望字符的外观创建样式:

.20char{font-size: 20px}
.50char{font-size: 10px}

然后在 Angular 中,将 ng-model 绑定到该字段,您可以知道该字段有多少个字符:

$scope.fontsize = "20char";

if($scope.field.length <= 20)
         {
             $scope.fontsize = "20char"
         } else if ($scope.field.length > 20 && $scope.field.length <= 50)
         {
             $scope.fontsize = "50char"
         }

然后在 HTML 中将变量 fontsize 绑定到 ng-class。

看到变量fontsize的值必须和类名匹配。

我认为应该可以。

【讨论】:

    【解决方案2】:
    <!DOCTYPE html>
    <html>
    <head>
        <title>change font size according to text length</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    </head>
    <body>
    <!--change text inside below division if the string length is 20 or more it's font size will be 14px else 50px-->
    <div id="text">Hello There I'm testing this text font size...!!!</div>
    
    <script type="text/javascript">
        jQuery( document ).ready(function() {
            var length = jQuery('#text').html().length;
            //change length at which you want to change font-size
            if(length >= 20){
                //enter font-size if text is long
                $("#text").css({'font-size':'14px'});
            } else {
                //enter font-size if text is short
                $("#text").css({'font-size':'50px'});
            }
        });
    </script>
    </body>
    </html>
    

    您可以根据需要更改值...! :) 此解决方案适用于 JQuery。

    【讨论】:

      【解决方案3】:

      name 很长时,使用ng-class 将类附加到元素

      <div id="name" ng-class="{'long': (profile.name.length > 20), 'verylong': (profile.name.length > 40)}">{{profile.name}}</div>
      

      然后使用该类更改 CSS 中的字体大小。

      【讨论】:

      • 您也可以将该表达式拉出到您作用域的对象中并将其传递进去。这样会更容易测试并且看起来更好。
      • @ste2425 我知道这是一篇很老的帖子,但如果你(或其他人)能展示一个例子就好了
      猜你喜欢
      • 2014-07-24
      • 1970-01-01
      • 2011-05-13
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 2015-08-28
      • 1970-01-01
      相关资源
      最近更新 更多