jquery datatable - set column width and wrap text

后端 未结 2 573
萌比男神i
萌比男神i 2020-12-17 21:54

We are using the Scroller plugin for our jquery data table to allow virtual scrolling. However, we have requirement to support text wrapping inside a cell, as user would lik

相关标签:
2条回答
  • 2020-12-17 22:03

    Found the solution by wrapping the column data in a div and setting the white-space, width css properties for the div.

    Fiddler:https://jsfiddle.net/Vimalan/2koex0bt/6/

    JS

    $('#example').DataTable( {
            data:           dataList,
            deferRender:    true,
            scrollX:        true,
            scrollY:        200,
            scrollCollapse: true,
            scroller:       true,
            searching:      false,
            paging:         true,
            info:           false,
            columns: [
                    { title: "ID", data: "ID" },
                    { title: "First Name", data: "FirstName" },
                    { title: "Change Summary", data: "LastName"},
                    { title: "Details", data: "Details" },
                    { title: "Country", data: "Country" }               
                ],
                columnDefs: [
                    {
                        render: function (data, type, full, meta) {
                            return "<div class='text-wrap width-200'>" + data + "</div>";
                        },
                        targets: 3
                    }
                 ]
        } );
    

    CSS

    .text-wrap{
        white-space:normal;
    }
    .width-200{
        width:200px;
    }
    
    0 讨论(0)
  • 2020-12-17 22:07

    Not sure if you add in stylesheets or not, but set your table-layout to fixed and add in the white-space. Currently you are using white-space:no-wrap which negates what you're trying to do. Also I set a max-width to all your td's so this will happen whenever there is overflow.

    Add this at the end of your jQUery

    https://jsfiddle.net/2koex0bt/5/

    $(document).ready(function(){
        $('#example').DataTable();
        $('#example td').css('white-space','initial');
    });
    

    If you want to just use the api, do this ( add in anymore CSS to change the styling ).

    If you want to do it with CSS, do this:

    table {
      table-layout:fixed;
    }
    table td {
      word-wrap: break-word;
      max-width: 400px;
    }
    #example td {
      white-space:inherit;
    }
    
    0 讨论(0)
提交回复
热议问题