Display DataTables columns at natural width

怎甘沉沦 提交于 2019-12-11 11:29:37

问题


I'm working with the DataTables library, and I'm using the autoWidth option to have DataTables set column widths automatically, as well as the Scroller plugin to fix headers and page data from the server.

This combination looks beautiful when my table has a large number of columns, but when it has just a few columns, the autoWidth setting makes them cartoonishly large.

Here's an example:

http://live.datatables.net/rizuvaza/2/edit

What I'd like is for the table to be only as wide as necessary for its content, and no wider. Sometimes this will mean that the content is too wide for the viewport and must be horizontally scrolled, and sometimes this will mean that the content is narrower than the viewport, in which case I don't want it to consume the whole horizontal space.

I've found a couple of approaches that work if I'm willing to hard-code a maximum width for the table, but doing so relies on me writing code to estimate the width of the columns myself. Obviously this is dependent on a wide variety of difficult measurements (font size, content width, etc) that I'd really rather leave up to DataTables.

Is there some way to configure DataTables, or use wrapping DOM elements and styles, such that it will always draw a table using only the width necessary?


回答1:


Well - dont know if that it was you are looking for - but if you set

#example {
    display: block;
}

and run a columns().adjust() right after initialisation

var table = $('#example')
    .DataTable()
    .columns()
    .adjust()
    .draw();

then the columns will be shrinked to the absolute minimum size.
demo -> http://jsfiddle.net/j5h9ob12/1/


Update, edited titles in the fiddle to emphasize the point.



来源:https://stackoverflow.com/questions/28868056/display-datatables-columns-at-natural-width

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