HTML Table Solution Max Height Limit For Rows Or C

2020-02-01 17:53发布

I am working on a very simple javascript solution which is useful when using overflow-x:auto in tables, script to decrease rows height by increasing table width until rows shrink that desirable height, (i also found other questions with same height problem).

Now only 2 things are left to complete this script:

  1. Get and Check Table Every Row Height Optimal Way (Without this its nearly useless)
  2. Code Simplification if possible.

My Javascript (only checks for a specific row) :

var h = document.getElementsByTagName('table')[0].rows[1].offsetHeight;
if (h > 200) {
document.getElementsByTagName('table')[0].style.width = "2000px";


var h = document.getElementsByTagName('table')[0].rows[1].offsetHeight;
if (h > 200) {
document.getElementsByTagName('table')[0].style.width = "3000px";


var h = document.getElementsByTagName('table')[0].rows[1].offsetHeight;
if (h > 200) {
document.getElementsByTagName('table')[0].style.width = "4000px";

}
}
}

Please help me on this...

I think maybe there a simple code which i dont know because i am beginner in javascript, but you guys may know that simple code...

EDIT: Finally this is working code if you want to limit table rows height:

var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
    while (row.offsetHeight > 160 && j < 4000) {
        j += 300;
        table.style.width = j + 'px';
    }
}

OR

for (var i = 0, row; row = document.getElementsByTagName('table')[0].rows[i]; i++) {
    if (row.offsetHeight > 200) {
        document.getElementsByTagName('table')[0].style.width = "1500px";
        if (row.offsetHeight > 200) {
            document.getElementsByTagName('table')[0].style.width = "2000px";
            if (row.offsetHeight > 200) {
                document.getElementsByTagName('table')[0].style.width = "2500px";
            }
        }
    }
}

标签: javascript
1条回答
够拽才男人
2楼-- · 2020-02-01 18:21

No one Answered this question but i found the solution myself:

Both will work:

var i = 0,
    j, row, table = document.getElementsByTagName('table')[0];
while (row = table.rows[i++]) {
    j = 1000;
    while (row.offsetHeight > 200 && j < 2500) {
        j += 500;
        table.style.width = j + 'px';
    }
}

OR

for (var i = 0, row; row = document.getElementsByTagName('table')[0].rows[i]; i++) {
    if (row.offsetHeight > 200) {
        document.getElementsByTagName('table')[0].style.width = "1500px";
        if (row.offsetHeight > 200) {
            document.getElementsByTagName('table')[0].style.width = "2000px";
            if (row.offsetHeight > 200) {
                document.getElementsByTagName('table')[0].style.width = "2500px";
            }
        }
    }
}
查看更多
登录 后发表回答