使表中的所有单元格具有等于最宽单元格宽度的相同宽度 [英] Make all cells in a table have the same width equal to widest cell width

查看:108
本文介绍了使表中的所有单元格具有等于最宽单元格宽度的相同宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不使用固定宽度的情况下,表格中所有单元格的宽度是否可以等于最宽单元格的宽度。

Is it possible to have the same width on all cells in a table that is equal to the widest cell's width without using fixed widths.

推荐答案

是的。

<table>
    <tr>
        <td>short</td>
        <td>longer</td>
        <td>the longest cell</td>
    </tr>
</table>





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

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

$cells.each(function () {
    $(this).width(max);
});

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

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

As @connexo pointed out in the comments some more logic is needed to handle the case when the table would be larger than its maximum size:

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);
});

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

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

And this is a version based on ECMA5 that doesn't require 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);
});

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

这篇关于使表中的所有单元格具有等于最宽单元格宽度的相同宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆