简体   繁体   English

如何从JavaScript调整表格列的宽度

[英]How to resize table columns width from JavaScript

I have a problem with javascript. 我的javascript有问题。
I have a list of table cells stored at TabList. 我有一个存储在TabList的表格单元格列表。
I want to find the maximum width, and then set this width to all of them. 我想找到最大宽度,然后将此宽度设置为所有宽度。
A sample code is here, but the setting of the width is not working. 此处有示例代码,但宽度设置不起作用。

var MaxTabWidth = 0;
for (var i = 0; i < TabList.length-1; i++)
{
  if (TabList[i].offsetWidth>MaxTabWidth) 
    MaxTabWidth = TabList[i].offsetWidth;
}

for (var i = 0; i < TabList.length-1; i++)
{
  TabList[i].style.width = MaxTabWidth+"px";
  // TabList[i].width = MaxTabWidth+"px";
  // TabList[i].offsetWidth = MaxTabWidth+"px";
}

I have commented my attempts.. 我评论了我的尝试..
Any help? 有帮助吗?
This didn't do the trick for me.. 对我来说不起作用..

update: 更新:
I am sure TabList is a list of Cells because I was checking the className. 我确定TabList是一个Cells列表,因为我正在检查className。
I am looping until TabList.length-1, because I want the last cell to fill the rest of the table's width. 我循环到TabList.length-1,因为我希望最后一个单元格填充表格宽度的其余部分。

I would suggest you remove all css/styling from the page and testing it to isolate the problem. 我建议你从页面中删除所有的CSS /样式并测试它以隔离问题。 Things like this are often complicated by css. 像这样的事情往往因css而变得复杂。

If you set the width of the entire table to --i*MaxTabWidth. 如果将整个表的宽度设置为--i * MaxTabWidth。 Would that evenly distribute the columns? 这会平均分配列吗? Suppose your table is named myTable. 假设您的表名为myTable。

document.getElementById('myTable').width = new String(--i*MaxTabWidth)

Edit: Also wouldn't 编辑:也不会

for (var i = 0; i < TabList.length-1; i++)

skip the last column by stopping at TabList.length-2? 通过停在TabList.length-2跳过最后一列?

For what it is worth, in jQuery this can be done with the following script where your table has the id of "myTable". 对于它的价值,在jQuery中可以使用以下脚本完成,其中表的id为“myTable”。 If you have enough control over the environment to add in a framework, I would highly recommend it since it makes tasks like these much easier. 如果您对框架中添加的环境有足够的控制权,我会强烈推荐它,因为它可以使这些任务变得更加容易。

    var maxWidth = 0;

    $("#myTable td").each(function() {
        if ($(this).width() > maxWidth) {
            maxWidth = $(this).width();
        }
    });
    $("#myTable td").width(maxWidth);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM