1. 程式人生 > >div裡面的內容超出自身高度時,顯示省略號

div裡面的內容超出自身高度時,顯示省略號

1.給DIV設定屬性:width: 200px; text-overflow: ellipsis; overflow: hidden; 當div裡面的內容總寬度找過 200PX的時候,超出的部分會以“...”的形式顯示。

2.上面那個案例之適用於單行文字的現實,才會有效。但當div裡面的內容出現多行的時候則不能達到預期的效果。下面是解決多行的時候顯示“...”的方案。

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title></title>  
  5.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  6.     <script type="text/javascript">  
  7.     $(function () {  
  8.         $(".figcaption").each(function (i) {  
  9.             var divH = $(this).height();  
  10.             var $p = $("p", $(this)).eq(0);  
  11.             while ($p.outerHeight() > divH) {  
  12.                 $p.text($p.text().replace(/(\s)*([a-zA-Z0-9]+|\W)(\.\.\.)?$/, "..."));  
  13.             };  
  14.         });  
  15.         });  
  16.     </script>  
  17.     <style>  
  18.         .figcaption  
  19.         {  
  20.             background: #EEE;  
  21.             width: 410px;  
  22.             height: 3em;  
  23.             margin: 1em;  
  24.         }  
  25.         .figcaption p  
  26.         {  
  27.             margin: 0;  
  28.             line-height: 1.5em;  
  29.         }  
  30.     </style>  
  31. </head>  
  32. <body>  
  33.     <div class="figcaption">  
  34.         <p>  
  35.             You probably can't do it (currently?) without a fixed-width font like Courier. With  
  36.             a fixed-width font every letter occupies the same horizontal space, so you could  
  37.             probably count the letters and multiply the result with the current font size in  
  38.             ems or exs. Then you would just have to test how many letters fit on one line, and  
  39.             then break it up.</p>  
  40.     </div>  
  41. </body>  
  42. </html>