开发者

How can I clip text and append an ellipsis when it is longer than desired?

I'm looking for a good way to appe开发者_开发知识库nd an ellipsis, "...", when I need to gracefully display a string that is too large and doesn't fit in the space that I want.

The way that I'm currently doing that is looking for a max length of characters that will fit in the space, then cut the string to that length and append the "..." . All that in the server-side.

In pseudocode should look like:

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

The problem is when I'm not using fixed-length fonts, it could be displayed not in the way that I want (occupying all the space).

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


You can use the CSS3 text-overflow property with a value of ellipsis. This property was introduced in IE6 and later adopted by other major browsers, with Firefox 7 being the most recent to add support for it:

#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 will be the first browser to implement the two-value syntax for this property, allowing both left and right sides of the text to have a value, though this syntax is currently noted as at-risk by the working draft specification.


This page has a non-JS solution for older Firefox versions, but it's not perfect and has a couple of limitations.


You can use text-overflow: ellipsis;, but it's not supported by Firefox.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜