How can I crop text and add ellipsis when it is longer than desired?

I am looking for a good way to add the ellipsis "..." when I need to gracefully display an oversized line and not fit into the space I want.

What I'm doing now is finding the maximum length of characters that will fit into the space, and then cut the string to this length and add "...". All this is server side.

In pseudocode should look like this:

// I define this MAXCHARS var value by hunch
String outputString = MyLengthyString.SubString(0, MAXCHARS)
outputString.concatenate("...")
view.aLabelInThePage = outputString

The problem is that when I do not use fixed-length fonts, it may not display the way I want (taking up all the space).

Is there a way to get the desired results using just JavaScript and CSS? If not, is there a better way than mine?

+3
3

CSS3 text-overflow ellipsis. IE6, , Firefox 7 , :

#mySpan {
  /* IE 6+, Opera 11+, Chrome 1+, Safari 1.3+, Firefox 7+ */
  text-overflow: ellipsis;

  /* IE 8    */ -ms-text-overflow: ellipsis;
  /* Opera 9 */ -o-text-overflow: ellipsis;
}

Firefox 9 , , , .


, JS, Firefox, .

+6

text-overflow: ellipsis;, Firefox.

+1

Will the jquery width command work along with a second span tag that only shows "..."?

if ($("#mySpan").width() > 400) {
     $("mySpan").width(400);
     $("mySpanEllipsis").show();
} 
else {
     $("mySpanEllipsis").hide();
}

And your HTML looks like

<span id="mySpan"></span><span id="mySpanEllipsis">...</span>

Not tested, so use at your own risk :-).

0
source

Source: https://habr.com/ru/post/1754621/


All Articles