我使用下面的代码来动态显示名字:
<div id="name">{{profile.name}}</div>
屏幕尺寸始终是320px,如果名称很短,则可以正常工作,但如果名称很长,则名称会被分成两行,这会扰乱我的布局。因此,如果名称变得太长,我想自动减小字体大小...
那么,有没有办法查看div的内容并根据字符长度动态应用不同的字体大小呢?
发布于 2016-05-20 17:18:18
当name
很长时,使用ng-class
将类附加到元素
<div id="name" ng-class="{'long': (profile.name.length > 20), 'verylong': (profile.name.length > 40)}">{{profile.name}}</div>
然后使用该类更改CSS中的字体大小。
发布于 2016-05-20 17:38:23
<!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。
发布于 2016-05-20 21:32:01
根据您希望的角色外观创建样式:
.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的值必须与类的名称匹配。
我觉得应该能行得通。
https://stackoverflow.com/questions/37342621
复制相似问题