I have a table which has a header row and few rows for the body content.
Now these are actually 2 separate tables:
- for Header
- for Body content (which is part of another iframe)
I want that the widths should be same for 开发者_开发百科the column header and it's corresponding body content.
How can I ensure that both the widths are similar and the appearance would be similar as if they are part of the same table?
I am open to both CSS or Javascript fix..
Note: I'll not be able to use fixed col widths AND neither do I have control to merge into one table...
Maybe something like this? This will make your tables act as if thay where one
var table1 = document.getElementsByTagName('table')[0].getElementsByTagName('tr');
var table2 = document.getElementsByTagName('iframe')[0].contentDocument.getElementsByTagName('tr');
var tr = merge([table1,table2]);
var padding = 2; //set your padding to make up for difference from offsetwidth vs style width
var higestWidth = new Array();
for(var i in tr){
for(var j in tr[i].childNodes){
var td = tr[i].childNodes[j];
if(typeof td == 'object'){
if(higestWidth[td.cellIndex] == null || higestWidth[td.cellIndex] < td.offsetWidth){
higestWidth[td.cellIndex] = td.offsetWidth;
}
}
}
for(var j in tr[i].childNodes){
var td = tr[i].childNodes[j];
if(typeof td == 'object'){
td.setAttribute('width', higestWidth[td.cellIndex] - padding);
}
}
}
Almost forgot im using some of my own functions here, here thay come aswell
var foreach = function(object,loop){
for (var key in object) {
if (object.hasOwnProperty(key)) {
loop(object[key],key);
}
}
}
var merge = function(objectCollections){
var array = new Array();
foreach(objectCollections,function(objectCollection){
foreach(objectCollection,function(object){
array.push(object);
});
});
return array;
}
I sort of agree with Rodrigo, although I would set max-width and min-width, rather than just width like so:
.col-username {
max-width:150px;
min-width:150px;
}
.col-email {
max-width:200px;
min-width:200px;
}
Otherwise, the actual size can depend on the table cell content and available space.
If it is not important that the table be "fluid", you can define classes for each of your columns and style them with css. Ex:
.col-username { width:150px; }
.col-email { width:200px; }
and so on.
Edit: here is an example I just found that uses CSS to achieve this effect.
You should be using <thead>
and <tbody>
if you can.
<table>
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 / Col 1</td>
<td>Row 1 / Col 2</td>
<td>Row 1 / Col 3</td>
</tr>
<tr>
<td>Row 2 / Col 1</td>
<td>Row 2 / Col 2</td>
<td>Row 2 / Col 3</td>
</tr>
...
</tbody>
</table>
Unless there's a reason you have separate tables, it would be much simpler to do it this way.
精彩评论