简体   繁体   English

按比例调整表的列大小

[英]Resize a table's columns proportionaly

Is there any Javascript library that can resize table in the next way: 是否有可以通过以下方式调整表大小的Javascript库:

if I change size of a column, all the columns to the right of this one should be resized proportionaly to it's current size. 如果我更改一列的大小,则该列右边的所有列均应按其当前大小按比例调整大小。

For example: 例如:

We have a table with 4 columns: 我们有一个包含4列的表格:

11px | 11像素| 20px | 20px | 10px | 10px | 30px 30像素

Total width of the table is 71px. 表格的总宽度为71px。

So, if I change width of the second column by 20px, the all columns located to the right of this column should change it's size proportionaly to it's current size. 因此,如果我将第二列的宽度更改为20px,则位于此列右侧的所有列均应按其当前大小按比例更改其大小。 So, for this example the table should looks like: 因此,对于此示例,该表应如下所示:

11px | 11像素| 40px | 40px | 5px | 5px | 15px 15像素

So, the width for the third column is calculating in this way: 因此,第三列的宽度是以这种方式计算的:

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

For the fourth: 对于第四:

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

Total width should remain the same as in init table: 71px(for this example). 总宽度应与初始化表中的宽度相同:71px(对于此示例)。

Here's a fiddle http://jsfiddle.net/ngZEB/ 这是一个小提琴http://jsfiddle.net/ngZEB/

An explanation of the code, because it turned out a little messy.. 对代码的解释,因为结果有点混乱。

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]
}

Basically what I'm doing is a bunch of calculations that I can't really explain well enough. 基本上,我正在做的是一堆计算,我无法真正解释得很好。 I hope you understand my answer. 希望您理解我的回答。 All the best! 祝一切顺利!

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

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