开发者

Javascript: Adding ellipsis to HTML text according to container size

I have a div which contains text. The text should be shortened to two lines and "..." added at the end to point that there's more.

Since the font and font size may vary according to different users' settings (for ex开发者_如何学编程ample: browser "text size" settings, different browsers, etc.), I need to do this dynamically on the client side.

What is the best strategy to do this?

Thanks.


There are a few CSS features that Microsoft pioneered and has had available to developers in Internet Explorer for a long time now. One of those features is the text-overflow property, which is now in CSS3 and has implementations in Safari, and Opera. However, firefox still does not support this feature.

For a cross browser JavaScript implementation of the ellipsis feature for the jQuery framework, you may be interested in checking out the following article:

  • Ajaxian - Text-Overflow for Firefox via jQuery

UPDATE:

Since jQuery is not an option, you may want to check the following:

  • Javascript Tutorial - How to Auto Ellipse Text
  • JavaScript Ellipsis or Cross-Browser "truncate with dots"
  • Ajaxian - Ellipsis or "truncate with dots" via JavaScript


You need to define the number of characters in the text you want visible. Then walk through the text with a for loop, until you reach your defined number of characters while saving the characters you've been through into a string variable. Once you reach the defined number of characters, the for loop ends and you append the string "..." to the build string variable. That's your new text for the container. Here's some code:

nchars = 50;
div = document.getElementById("your_div_with_text");
divText = div.innerHTML;
newDivText = "";
for(var i = 0; i < nchars; i++){
   newDivText += divText[i];
}
newDivText += "...";
div.innerHTML = newDivText;

As for the issue with the fonts and font size, you could probably just set a CSS class containing font size and font family, that looked the best in all browsers.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜