按比例调整表格列的大小

时间:2013-11-18 16:04:02

标签: javascript jquery html-table

是否有任何Javascript库可以通过下一种方式调整表格大小:

如果我更改列的大小,则应根据当前大小的比例调整此列右侧的所有列的大小。

例如:

我们有一个包含4列的表格:

11px | 20px | 10px | 30PX

该表的总宽度为71px。

因此,如果我将第二列的宽度更改为20px,则位于此列右侧的所有列应根据其当前大小按比例更改其大小。因此,对于此示例,该表应如下所示:

11px | 40px | 5px | 15px的

因此,第三列的宽度以这种方式计算:

10 - 10 /(10 + 30)* 20 = 5px

第四个:

30 - 30 /(10 + 30)* 20 = 15px;

总宽度应与init表中的相同:71px(对于此示例)。

1 个答案:

答案 0 :(得分:0)

这是一个小提琴http://jsfiddle.net/ngZEB/

对代码的解释,因为它变得有点凌乱..

var cols = document.getElementsByTagName('td'), 
    Widths = [11,20,10,30],
    totalWidth = 71,
    CommonWidth,
    WidthLeft,
    ColThatWillBeChaned,
    coef = [];

//setting the widths of the actual elements
for(i=0;i<4;i++){
    cols[i].style.width = Widths[i]+'px';
    coef[i] = Widths[i]/totalWidth;
}

//Pretty self explanatory
ColThatWillBeChaned = 1;
Widths[ColThatWillBeChaned] += 20;


//Initializing width that will be left after the new column width has taken place
WidthLeft = totalWidth;

//The width that the elements to the right are sharing before the changes
CommonWidth = 0;
for(i=0;i<4;i++){
    if(i<=ColThatWillBeChaned){
        WidthLeft -= Widths[i];        
    }else{
        CommonWidth += Widths[i];
    }
}
for(i=(ColThatWillBeChaned+1);i<4;i++){
    //The new coefficient that determines what portion of the new width the 
    //current element will be taking
    coef[i] = Widths[i]/CommonWidth;

    //actually setting the width
    Widths[i] = WidthLeft*coef[i]
}

基本上我正在做的是一堆我无法解释得很好的计算。我希望你理解我的答案。一切顺利!