First, the use of CSS implementation
-
1 . SLH {2width:200px; 3 Display:block; 4 Overflow:hidden; 5 white-space:nowrap; 6 -o-text-overflow:ellipsis; 7 text-overflow:ellipsis; 8 }
Pros: Easy to use
Cons: If you set
The ie8+ is truncated directly to the width of the width. The ellipsis is not displayed.
And if the height is not specified. The text is also wrapped in a line display.
So add a style
. height20{height:20px;}
Second, the use of JS implementation
Another way is to use JS:
-
1 //truncate string, display ellipsis2 functionTextauto () {3$ (". Slh"). each (function(){4 varNowlen = $ ( This). HTML (). length;5 varwidth=$ ( This). CSS ("width"). Replace ("px", "")-0;6 varNeedlen = WIDTH/14;7 if(Nowlen >Needlen) {8 varNowword = $ ( This). HTML (). substr (0,needlen) + ' ... ';9$( This). HTML (nowword);Ten } One }); A}
Pros: The ellipsis is displayed by automatically calculating the number of characters that appear based on the width.
Disadvantages:
1, but if it is a letter. It is possible to intercept a short width based on the number of calculations.
2. Interception must be performed after the contents of the DOM have been populated. You need to be aware of how long the method executes.
CSS implementation ellipsis