2013-05-13 149 views
1

我在這裏要做的是創建一個帶有Javascript(成功)的表格,其格式爲,最大寬度爲300px隱藏表的溢出?

現在,如果我的表比300像素寬我想溢出隱藏,但會發生什麼是桌秤其寬度降低到每即使我設置<td>到爲不同寬度的時間爲300px:

<style> 
#tablespace { 
margin:auto; 
position:relative; 
width:300px; 
overflow:hidden;  
} 
</style> 

<button onclick="CreateTable()" >Try it</button> 
<div id="tablespace"> 
    <p id="tablespace"> </p> 
</div> 

<script> 
function CreateTable() 
{ 
    var tablecontents = ""; 
    tablecontents = "<table border=1>"; 
//number of rows 
for (var i = 0; i < 3; i ++) 
{ 
tablecontents += "<tr>"; 
//number of columns 
    for (var a = 0; a < 5; a ++) 
    { 
     tablecontents += "<td height= 50, width= 100>" + i + "</td>";  
    } 
    tablecontents += "</tr>"; 
} 
tablecontents += "</table>"; 
document.getElementById("tablespace").innerHTML = tablecontents; 
} 
</script> 

那麼,我已經使用了一個小區的100像素50像素和寬度的高度,因爲我的div最大寬度爲300像素,我應該只看到2個半細胞,然後剩下的就是隱藏的,但事實並非案件。

我明白這可能是一個基本的錯誤,但我不知道。

回答

0

在表格單元上使用min-width

演示:http://jsfiddle.net/jUqvj/

簡單的例子:

CSS:

div { 
    max-width: 300px; 
    border: 1px solid #f00; 
    overflow: hidden; 
} 
#table1 td { 
    min-width: 100px; 
    border: 1px solid #0ff; 
} 
#table2 td { 
    width: 100px; /* here it's not effective as desired */ 
    border: 1px solid #0ff; 
} 

HTML:

<pre>With min-width on table cells</pre> 
<div> 
    <table id="table1"> 
     <tr> 
      <td>Col1</td> 
      <td>Col2</td> 
      <td>Col3</td> 
      <td>Col4</td> 
     </tr> 
     <tr> 
      <td>Col1</td> 
      <td>Col2</td> 
      <td>Col3</td> 
      <td>Col4</td> 
     </tr> 
     <tr> 
      <td>Col1</td> 
      <td>Col2</td> 
      <td>Col3</td> 
      <td>Col4</td> 
     </tr> 
    </table> 
</div> 
<hr><br> 
<pre>Without min-width on table cells</pre> 
<div> 
    <table id="table2"> 
     <tr> 
      <td>Col1</td> 
      <td>Col2</td> 
      <td>Col3</td> 
      <td>Col4</td> 
     </tr> 
     <tr> 
      <td>Col1</td> 
      <td>Col2</td> 
      <td>Col3</td> 
      <td>Col4</td> 
     </tr> 
     <tr> 
      <td>Col1</td> 
      <td>Col2</td> 
      <td>Col3</td> 
      <td>Col4</td> 
     </tr> 
    </table> 
</div> 
0

嘗試改變這種(我不知道這是否實際上已經在代碼中):

tablecontents += "<td height= 50, width= 100>" + i + "</td>"; 

tablecontents += '<td height="50px", width="100px">' + i + "</td>"; 

BTW,我會建議跳過所有THES HTML3參數和做這一切由單獨的CSS類像

tablecontents += '<td class='croppedTable'>' + i + "</td>"; 

<style> 
#tablespace { 
margin:auto; 
position:relative; 
width:300px; 
overflow:hidden;  
} 

.croppedTable { 
... some styles ... 
} 
.croppedTable TD { 
... some additional styles ... 
width: 100px; 
height: 50px; 

} 
</style>