简体   繁体   中英

DataTables auto dynamic column width

I have a datatable being populated by json data via ajax. I have the autoWidth property set to false. What I am looking to do is set certain columns to have a width based on the content that is returned.

What it looks like is happening during pagination is that the table is being redrawn or something every page I go to. This is causing the columns to bounce around in different positions and/or changing the width of that column. I can't seem to find what I need to do.

What I am looking for is once the table is loaded with data the first time each column min-width is set to the largest data content returned in that row. I hope I am explaining that correctly. What I ultimately want is the columns to not adjust widths after the data is loaded the first time. So not on pagination or sorting of columns.

The only thing I did try was table.columns.adjust().draw(); but I put in the the drawCallback function as I didn't know where else to do it. That didn't seem to do anything for me.

I have googled for long enough of this and was hoping someone could at least point me in the right direction or provide a little help.

I can't think of a good way of doing this using DataTables itself, since the column widths have to be declared upon initialization.

However, you can do something pretty similar using vanilla JavaScript and CSS after everything has loaded:

    // get the table headers into an array
    let tableHeaders = document.querySelectorAll("#YOUR-TABLE-ID thead th");

    tableHeaders.forEach((element) => {
        // get the computed width for the column
        const computedWidth = window.getComputedStyle(element).getPropertyValue("width");
        // set CSS min-width on element
        element.style.minWidth = computedWidth;
    });

Widths will automatically be applied to all <td> elements within the same column as a <th> element that has width styles.

Also be aware that DataTables assigns a width style property to each <th> element.

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