幅が固定されている html div があります。その中にテキストコンテンツを入れたいと思っています。テキストが長すぎる場合は、テキストを切り捨てます。ただし、text-overflow: ellipsis
プロパティとは異なり、途中で切り捨てたい。あなたが思いついた面白いアイデアがあれば聞きたいです。
1815 次
3 に答える
2
「テスト」div を使用して値のサイズを決定し、目的の幅に収まるまで中央をトリミングしてサイズを変更できます。
このjsfiddle の例は大まかな実装です。サイズ + 省略記号がコンテナーの幅より小さくなるまで、一度に 1 文字ずつ値を小さくします (これはかなり簡単に改善できます)。
ジャバスクリプト/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>
一般的な概念は機能的ですが、特にページにこれらの値が多数ある場合は、あまりパフォーマンスが高くありません。
前
後
これを改善するためのいくつかの追加の考慮事項は、
- 単語が途切れないように、文字ではなく単語ごとにトリムする
- 値をより速くトリミングするためにいくつかの基本的な推測を追加します (例: テキストの幅が 1000 でコンテナーが 100 のみの場合、値の ~80% をかなり簡単に切り取って、そこから一度に 1 つずつトリミングできます)。
- div に title 属性を設定して、ホバー ツールチップに完全な値が表示されるようにします。
于 2012-07-24T19:16:35.853 に答える
0
質問は、ここSOで以前に尋ねられました。ここでの私の答えは、より多くの手がかりを与えるでしょうか?
于 2012-07-24T18:47:34.703 に答える
0
これを行うには .substring を使用できます。幅が 10 文字と省略記号を保持できるとします。次のようにすることができます。
var myText = "This is a sentence that needs to be reduced";
myText = myText.substring(0,5) + "..." + myText.substring(myText.length-5);
于 2012-07-24T18:36:12.497 に答える