简体   繁体   English

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

[英]javascript AngularJS automatic change font size when wrapping of label

I have a project developed using AngularJS and Bootstrap. 我有一个使用AngularJS和Bootstrap开发的项目。 The system should support all languages, and all the labels should switch whenever the user selects a different language. 系统应支持所有语言,并且每当用户选择其他语言时,所有标签都应切换。

This is working ok except for one thing: The same sentence displays different length in different languages. 除以下几点外,这还行得通:同一句子用不同的语言显示不同的长度。 As a result, some labels exceed the allocated width and spoil the way things are being display. 结果,一些标签超过了分配的宽度,并且破坏了事物的显示方式。

Due to the structure of the page, I cannot use wrapping. 由于页面的结构,我不能使用自动换行。

I would like to detect whenever a label's length exceeds the allocated space and automatically reduce the font size till it fits (you can see an example in Google Translate). 我想检测标签的长度何时超过分配的空间,并自动减小字体大小直到适合为止(您可以在Google Translate中看到一个示例)。

Any suggestions how this can be done? 任何建议如何做到这一点?

Thanks. 谢谢。

It's a little tricky and not so generic but it's definitely direction. 这有点棘手,不是那么通用,但这绝对是方向。 Of course that you will need to do some fine tunings for your needs. 当然,您需要根据需要进行一些微调。

I was created a directive for this based on (with my fixes) this answer . 我创建了一个directive对于此基础上(与我修复)这个答案

Read the comments in the code: 阅读代码中的注释:

 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 http://jsbin.com/dokuwew/edit?html,css,js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM