Autosize HTML table cell height based on content when rowspan is involved

给你一囗甜甜゛ 提交于 2019-12-05 09:37:05

This sets the last row of cells to the correct height (demo):

function grow(td) {
    var table, target, high, low, mid;

    td = $(td);
    table = td.closest('table');
    target = table.height();
    low = td.height();

    // find initial high
    high = low;
    while (table.height() <= target) {
        td.height(high *= 2);
    }

    // binary search!
    while (low + 1 < high) {
        mid = low + Math.floor((high - low) / 2);
        td.height(mid);
        if (table.height() > target) {
            high = mid;
        } else {
            low = mid;
        }
    }

    td.height(low);
}

$('tr:last-child td').each(function() { grow(this); });

​ It should be trivial to convert this into plain JavaScript.


Update: For more complicated tables, you'll want to replace the last line with this (demo):

$.each($('td').get().reverse(), function() { grow(this); });

​ The idea is to call grow() on every cell, starting with the last row and working upwards.

considering table id="mytable" it would be:

    $("#mytable").find("td").each(function(){ 

    var ContentHeight = $($(this).html()).height();
    $(this).height(ContentHeight);

 });

at the end of the your page create a javascript code and let it do it for you:

 <script type="text/javascript"> 
document.getElementById("idOfTd").style.height="100px";
</script>

I think it better create like this http://jsfiddle.net/miqdad/w9QYB/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!