简体   繁体   中英

Dynamic Table Width

I have a table cell in which other tables are displayed (with background colors). The inner tables aren't always shown; they can be hidden via a button (change class with jQuery). Now I want the outer cell to always be filled with color. That means if only one table is displayed, its width should be 100%. When two are displayed, each width should be 50%, and so on. How am I supposed to solve this?

Here's an example:

... 
<td>
<table class="show"><tr><td></td></tr></table>
<table class=""><tr><td></td></tr></table>
<table class="show"><tr><td></td></tr></table>
</td>
...

In this case, the width should be 50%

To change the width of your elements you can use jquery.

Here's the page explaining how.

You can change the width value with Jquery.

var count_table = $(".show").length;         // count ".show" elements

$(".show").each(function{                    // iteration on each ".show"
    var width = 100/count_table;             // % value of new width
    $(this).css("width", width+"%");         // CSS modification
});

This code is just adapted for one TD element. You need to iterate on each "td" too.

(I hope I answered your problem)

Here is another way: http://jsfiddle.net/ypJDz/1

A bit too complicated for what you need, but a great deal of possibility to expand.

function resizeTables() {
    var baby = $("td > table.show"),
        amount = baby.length,
        mother = $("body");

    baby.width(function () {
        var w = mother.width() / amount;
        return w;
    });
}

resizeTables();

$("button").click(function () {
    var $this = $(this),
        ID = $this.index() + 1;

    $("td > table:nth-child(" + ID + ")").toggleClass("show");
    resizeTables();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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