javascript AngularJS在包装标签时自动更改字体大小

时间:2016-03-20 09:45:30

标签: javascript html angularjs twitter-bootstrap

我有一个使用AngularJS和Bootstrap开发的项目。系统应该支持所有语言,并且只要用户选择不同的语言,所有标签都应该切换。

除了一件事之外,这是正常的:同一个句子在不同的语言中显示不同的长度。结果,一些标签超出了分配的宽度,破坏了显示方式。

由于页面的结构,我无法使用包装。

我想检测标签的长度是否超过分配的空间并自动缩小字体大小直到它适合(您可以在Google翻译中看到一个示例)。

有关如何做到这一点的任何建议吗?

感谢。

1 个答案:

答案 0 :(得分:2)

这有点棘手而且不那么通用,但绝对是方向。当然,您需要根据自己的需要做一些精细的调整。

我根据(使用我的修正)answer为此创建了directive

阅读代码中的注释:

angular.module('myApp', []).
controller('ctrl', function(){}).
directive('label', function() {
  function resize_to_fit(element) {
    // check the font-size. In the second time it will return the value with "px" so we need to remove it.
    var fontsize = element.css('font-size');
    if (fontsize.length) {
      fontsize = fontsize.replace('px', '');
    }
    // check the current height 
    var orgHeight = element.css('white-space','normal').height();
    // check the height it should be in one line
    var singleLineHeight = element.css('white-space','nowrap').height();

    // check if the element have 1 line or more
    if(orgHeight > singleLineHeight) {
      // reduce the font size in 1
      element.css('fontSize', parseFloat(fontsize) - 1);
      resize_to_fit(element);
    }
    else {
      // finally remove the "white-space" - you can remove this line if you don't need it.
      element.css('white-space','normal');
    }
  }

  return {
    link: function(scope, element) {
      resize_to_fit(element);
    }
  }
});
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div ng-app="myApp" ng-controller="ctrl" class="container">
  <label class="col-xs-1">Lorem Ispum</label>
</div>

http://jsbin.com/dokuwew/edit?html,css,js