2013-12-21 192 views
2

我試圖做一個表儘可能小。一個單元可能有更多的內容,然後所需的寬度,所以我設置「最大寬度」。所以在某些情況下,內容會被分成更多行,這很好。 然而,該行以兩次破發的表格單元格保持在最大寬度,而它可能是更小的,如果它會調整到現在破的內容。表單元格td,最大寬度顯示太多的空白,如果換行

很多的話,很容易看:http://jsfiddle.net/G3bcB/10/

<p>Too much white space:</p> 
<table> 
    <tr> 
     <td class="leftcell">long texttext overflow</td> 
     <td>B</td> 
     <td>C</td> 
    </tr> 
</table> 
<p>Upper table could have same width:</p> 
<table> 
    <tr> 
     <td class="leftcell">long texttext</td> 
     <td>B</td> 
     <td>C</td> 
    </tr> 
</table> 

table { width: auto; } 
td { border: 1px solid black; } 
td.leftcell { max-width: 100px; } 

我不知道這是否是HTML的一個特點,但對我來說似乎是錯誤的。

是否有可能使現場更小(使用標準的CSS)?

+0

你需要顯示所有的文本?得到它進入TD的唯一方法是:(1)使之與剪裁,字體大小等較小;(2)把一個div在TD和溢出:隱藏,空白:NOWRAP等 – TimSPQR

+0

同問題出在FF,IE和Chrome上。如果你在那裏堅持一個
,在TD被最小化。我同意這看起來不對。 –

回答

0

沒有JavaScript你不能做到這一點。幸運的是它不是太複雜。我改變了類第一小區的leftcell1從下表中區分開來,並加長用於演示目的的字符串:

<td class="leftcell1"> 
    long texttext overflow long overflow 
</td> 

下面是更新jsFiddle

和JavaScript:

var el = $('.leftcell1'); 

//temporarily puts the text in the cell to measure it 
function getWidth(el, txt) { 
    el.html(txt); 
    return el.css('width').replace('px', ''); 
} 

//returns the string w/ the <br /> tags in the right place 
function splitString(maxWidth) { 
    var txtArr; 
    var presentTxt = ''; 
    var futureTxt = ''; 
    var finalTxt = ''; 
    //split the words up if longer than the max width 
    if (getWidth(el, el.html()) >= maxWidth) { 
     txtArr = el.html().split(' '); 
     //loop through the words and add them together 
     for (var i in txtArr) { 
      futureTxt += txtArr[i] + ' '; 
      //check if the string is longer than the max width 
      if (getWidth(el, futureTxt) > maxWidth) { 
       //It is. Add it to the final string with a <br /> 
       //and chop off the trailing space 
       finalTxt += presentTxt.substring(0, presentTxt.length - 1) + '<br />'; 
       futureTxt = presentTxt = txtArr[i] + ' '; 
      } else { 
       //it's not. Keep adding to it. 
       presentTxt = futureTxt; 
      } 
     } 
    } else { 
     finalTxt = el.html(); 
    } 
    //if there is anything leftover in futureTxt add it to finalTxt 
    if (futureTxt != '') { 
     finalTxt += futureTxt; 
    } 
    return finalTxt; 
} 
el.html(splitString(100)); 
+0

感謝代碼的和平! –

相關問題