2013-05-13 142 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>