最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

css - How to resize table columns width from JavaScript - Stack Overflow

programmeradmin0浏览0评论

I have a problem with javascript.
I have a list of table cells stored at 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 mented 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.
I am looping until TabList.length-1, because I want the last cell to fill the rest of the table's width.

I have a problem with javascript.
I have a list of table cells stored at 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 mented 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.
I am looping until TabList.length-1, because I want the last cell to fill the rest of the table's width.

Share Improve this question edited May 23, 2017 at 12:15 CommunityBot 11 silver badge asked Apr 30, 2009 at 15:30 StavrosStavros 6,14013 gold badges33 silver badges45 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

I would suggest you remove all css/styling from the page and testing it to isolate the problem. Things like this are often plicated by css.

If you set the width of the entire table to --i*MaxTabWidth. Would that evenly distribute the columns? Suppose your table is named 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?

For what it is worth, in jQuery this can be done with the following script where your table has the id of "myTable". If you have enough control over the environment to add in a framework, I would highly remend 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);
发布评论

评论列表(0)

  1. 暂无评论