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

最后都变了- 提交于 2019-12-22 05:19:26

问题


Is there a way to autosize HTML table height based on content? Also if it's a cell (or cells) next to a neighbor cell with multiple rowspans.

E.g. if I have a table like this (cell on the right has Rowspan="2" and height of the cell content = 600px, in each cell on the left height of the cell content = 150px):

there is a gap between 2 cell consents on the left because cells themselves autosized their height. I'd like it to look like this:

Where top cells automatically collapse to cell content height. Is there anyway to achieve this?


回答1:


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.




回答2:


considering table id="mytable" it would be:

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

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

 });



回答3:


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>



回答4:


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



来源:https://stackoverflow.com/questions/10919286/autosize-html-table-cell-height-based-on-content-when-rowspan-is-involved

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