使表中的所有单元格具有等于最宽单元格宽度的相同宽度

Pat*_*osa 4 html javascript css

是否可以在表中的所有单元格上具有相同的宽度,该宽度等于最宽单元格的宽度而不使用固定宽度.

And*_*cia 6

是的.

<table>
    <tr>
        <td>short</td>
        <td>longer</td>
        <td>the longest cell</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)
var max = 0,
    $cells = $('td');

$cells.each(function () {
    var width = $(this).width();
    max = max < width ? width : max;
});

$cells.each(function () {
    $(this).width(max);
});
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/uqvuwopd/1/

[编辑]

正如@connexo在注释中指出的那样,当表大于其最大大小时,需要更多的逻辑来处理这种情况:

var max = 0,
    $cells = $('td');

$cells.each(function () {
    var width = $(this).width();
    max = max < width ? width : max;
});

$table = $cells.closest('table');

if ($table.width() < max * $cells.length) {
    max = 100 / $cells.length + '%';
}

$cells.each(function () {
    $(this).width(max);
});
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/uqvuwopd/3/

[编辑]

这是一个基于ECMA5的版本,不需要jQuery:

var max = 0,
    cells = document.querySelectorAll('td');

Array.prototype.forEach.call(cells, function(cell){
    var width = cell.offsetWidth;
    max = max < width ? width : max;
});

var table = document.querySelector('table'),
    uom = 'px';

if (table.offsetWidth < max * cells.length) {
    max = 100 / cells.length;
    uom = '%';
}

Array.prototype.forEach.call(cells, function(cell){
    cell.setAttribute('style','width:' + max + uom);
});
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/uqvuwopd/4/