[英]dynamic text length limit based on div width
I am having a div which will be having dynamic width, based on the width I have to restrict the content within that div,I have created a filter which will cut the text and append "..." to the end of the string, but the issue is how we can assign the limit based on the dynamic width size 我有一个div将具有动态宽度,基于我必须限制该div内容的宽度,我创建了一个过滤器,它将剪切文本并将“...”附加到字符串的末尾,但问题是我们如何根据动态宽度大小分配限制
my code is as given below 我的代码如下所示
html HTML
<div ng-app="app" ng-controller="MainCtrl">
<div class="test" ng-style="myStyle">{{value | splice:12:' ...'}}</div>
</div>
script 脚本
angular.module('app', [])
.controller('MainCtrl', function ($scope) {
$scope.myStyle={};
$scope.myStyle.width = "150px";
$scope.value= "My value is anythinggggggggggggggggg";
})
.filter('splice', function () {
return function (value, max, tail) {
if (!value) return '';
max = parseInt(max, 10);
if (!max) return value;
if (value.length <= max) return value;
value = value.substr(0, max);
return value + (tail || ' …');
};
});
I've tried with a different appraoch for your problem. 我已尝试使用不同的appraoch来解决您的问题。 See if it helps:
看看它是否有帮助:
Instead of passing the limit
to the filter, am passing the width
of the element. 我没有将
limit
传递给过滤器,而是传递了元素的width
。
<div class="test" ng-style="myStyle">{{value | splice:myStyle.width:' ...'}}</div>
Now inside your filter: 现在在你的过滤器内:
function (value, max, tail) {
if(isNaN(max))
max = parseInt(max.slice(0,-2),10)/12;
if (!value) return '';
max = parseInt(max, 10);
// rest of your code
Am checking if it's a string. 我在检查它是否是一个字符串。 In case its a string, assuming you're passing
width
in format of 150px
. 如果它是一个字符串,假设你以
150px
格式传递width
。 So slicing the px
from the string. 所以从字符串切片
px
。 we've 150
now. 我们现在已经
150
岁了。
Now taking the least font size of 8 and dividing it by 8. So now the limit will be based on the width of the element. 现在取最小字体大小为8并将其除以8.所以现在限制将基于元素的宽度。
You can reuse the same filter
by passing the width as well as passing the limit directly. 您可以通过传递宽度以及直接传递限制来重用相同的
filter
。 It will suit for both the scenarios now. 它现在适合这两种情况。
Updated Answer
更新的答案
I've been looking at different solutions. 我一直在寻找不同的解决方案。 As you've mentioned in comments that the font-size may vary.
正如您在评论中提到的那样,字体大小可能会有所不同。 I guess better we go with simple CSS based approach in that case using
text-overflow
. 我想我们更好的是使用基于CSS的简单方法,在这种情况下使用
text-overflow
。
.test {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
Now whatever may be the font-size, the text will always be clipped. 现在无论是什么字体大小,文本将始终被剪裁。 Now in whichever elements you want to have this feature, add specific css class
clip-text
. 现在,无论您想要具有此功能的哪个元素,都要添加特定的css类
clip-text
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.