我有一个宽度固定的html div。我想在其中加入一些文字内容。如果文本太长,我想截断文本。但是,与text-overflow: ellipsis
属性不同,我希望在中间截断。我希望听到你有任何有趣的想法。
答案 0 :(得分:2)
您可以使用“test”div来确定值的大小,并通过修剪中间值来调整它们的大小,直到它符合所需的宽度。
这个jsfiddle example是一个粗略的实现。它一次缩小一个字符的值(可以很容易地改进),直到大小+省略号小于容器宽度
javascript / jQuery
// Text excision for generating middle ellipsis values to fit a specific size.
String.prototype.cutMiddleChar = function() {
var charPosition = Math.floor(this.length / 2)
return this.substr(0, charPosition) + this.substr(charPosition + 1);
};
String.prototype.insertMiddleEllipsis = function() {
var charPosition = Math.floor(this.length / 2)
return this.substr(0, charPosition) + '...' + this.substr(charPosition);
};
var w = 0,
t = '',
$test = $('.excision-test');
$('div').each(function() {
// re-usable $this
var $this = $(this);
// get current width, this is the width we need to fit the value to
w = $this.width();
// get current text value, we'll be manipulating this till it's sized right
t = $this.text();
// set our test div to the value (plus our ellipsis) for sizing
$test.text(t + '...');
//console.log(w);
//console.log($test.width());
// when the value's width is greater than the width of the container loop through to size it down
if ($test.width() > w) {
while ($test.width() > w) {
t = t.cutMiddleChar()
//console.log('str cut: ' + t);
$test.text(t + '...');
//console.log('str len: ' + t.length);
//console.log('width: ' + $test.width());
}
$this.text(t.insertMiddleEllipsis());
}
});
<强> CSS 强>
/* manipulate font-family, font-size as needed */
body {font-family:arial;font-size:12px;}
/* div and test div must use same formatting (font-size, font-family, etc) */
div {width:300px;border:1px solid red}
.excision-test {position:absolute;left:-10000em;width:auto;}
<强> HTML 强>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vel orci quis nunc vulputate tristique quis id tortor. Donec dui ante, condimentum quis iaculis ut, venenatis vel lorem. Etiam ullamcorper aliquam imperdiet. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis tincidunt ligula lorem. Pellentesque pharetra ipsum nec erat tempor vel sagittis libero volutpat. Donec malesuada convallis pharetra.
</div>
<div class="excision-test"></div>
一般概念是功能性的,但不是非常高效,特别是如果你在页面上有很多这些值。
之前
后
要改善这一点的一些额外考虑因素是
答案 1 :(得分:0)
您可以使用.substring来执行此操作。假设您的宽度可以容纳10个字符加上省略号,您可以执行以下操作:
var myText = "This is a sentence that needs to be reduced";
myText = myText.substring(0,5) + "..." + myText.substring(myText.length-5);
答案 2 :(得分:0)
此前有人问过这个问题。也许my answer here会提供更多线索?