2016-04-11 41 views
1

我有一個寬度設置爲100%的<table>。在<td>裏面是一個帶有文本字符串的div,如果文本寬度溢出,我想添加一個省略號。在調整瀏覽器大小時對文本使用CSS省略號

在JavaScript中,我將<div>的寬度設置爲<td>的寬度,並且此工作適用於加載(或刷新),但我無法使其工作onresize

(不用擔心什麼,我居然在這裏做什麼,這是一個更大的桌子,我簡化了這個問題的緣故的一部分。)

任何人都可以建議我怎麼能得到文本省略號-ify onresize

function doThis() { 
 
    $('.divClass').css('width', $(".tdClass").css('width')); 
 
}
.divClass { 
 
    width:0px; 
 
    white-space:nowrap; 
 
    overflow:hidden; 
 
    text-overflow:ellipsis; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body onload="doThis()" onresize="doThis()"> 
 

 
<table style="width:100%"> 
 
    <tr> 
 
     <td class="tdClass"> 
 
      <div class="divClass"> 
 
       the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog 
 
      </div> 
 
     </td> 
 
    </tr> 
 
</table> 
 

 
</body>

+0

請看看我的回答 – brk

回答

0

嘗試綁定調整與瀏覽器的窗口,如果不是身體屬性

$(window).resize(function(){ 
    doThis() 
}); 
+0

不幸的是,這也不起作用。 –

+0

你有沒有檢查'doThis'函數是否觸發調整大小? – vusan

+0

那麼你可以做一個alert(),它工作正常。 –

0

工作我想它可以只使用CSS來完成。 可以請你試試這個代碼

<!DOCTYPE html> 
<html> 
<head> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 

<style> 
    /* Added new style property */ 
table,tr,td,tbody{ 
    width:100%; 
    display:inline-block; 

} 
td{ 
    text-overflow:ellipsis; 
    overflow:hidden; 
    white-space:nowrap; 
} 
    /* New style property end her */ 
</style> 

</head> 
<body> <!-- //removed onload & onresize --> 

<table> 
    <tr> 
     <td> <!-- // removed the div --> 
      the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog 

     </td> 
    </tr> 
</table> 

</body> 
</html> 
+0

這對於每個TR只有一個TD有效,但每個數據行都有其他TD,所以'inline-block'使得TD堆疊,而不是並排坐在一起。 –

0

事業部是塊元素,所以如果你不給任何寬度,它會自動採取TD的寬度。意味着不需要腳本。

0

嘗試使表響應display:block屬性,以便div可以在調整大小時從td元素獲得適當的寬度。

table, thead, tbody, th, td, tr { 
    display: block; 
    height: auto; 
} 
+0

這可以在每個TR中使用單個TD,但是我在每個數據行中都有其他TD,所以'inline-block'使得TD堆疊而不是並排坐在一起。 –

相關問題