简体   繁体   English

数据表固定列与重复 header 列过滤不固定

[英]datatables fixed columns with duplicated header for column filtering not fixed

I duplicated my thead row for custom column search according this example根据此示例,我复制了用于自定义列搜索的 thead 行

Problem is that I have fixed columns 0 and 1 from left.问题是我从左边固定了第 0 列和第 1 列。 When I perform scroll right, second row which contains input for column filter is moving but the rest of column is sticky.当我向右滚动时,包含列过滤器输入的第二行正在移动,但列的 rest 是粘性的。 As I see css, that tr element is missing sticky position as the rest of fixed columns.正如我看到的 css,该 tr 元素缺少粘性 position 作为固定列的 rest。

How to fix it?如何解决?

this is my code这是我的代码

 $('#custom_list_details thead tr').clone(false)
        .addClass('head_filters')
        .appendTo('#custom_list_details thead');
      


 custom_list_details_table= $('#custom_list_details').DataTable({
    'order': [[1, 'asc']],
    "orderCellsTop": true,
    'fixedColumns': {
        'left': 2
    },
    "select":true,
    "keys": {
            "columns": ':not(:first-child)',
            "focus": ':eq(2)',
            "blurable": false

        },
    'colReorder': {
        'fixedColumnsLeft': 2
    },
    "ajax": '/customlist_table/'+$custom_list_id+'.json',

    "processing": true,
    'dom': 'lfr<"pull-right"B>tip',
    'buttons': [
    {"extend" : 'copyHtml5',"text":"Copy","className": 'btn btn-default btn-xs'},
    {"extend" : 'excelHtml5',"text": "XLS","className": 'btn btn-default btn-xs'},
    {"extend" : 'csvHtml5',"text": "CSV","className": 'btn btn-default btn-xs'},
    {
                text: 'Change table size',
                className: 'btn btn-primary btn-xs table-size-btn',
                action: function ( e, dt, node, config ) {
                    if ($('#custom_list_details').hasClass('compact') && $('#custom_list_details').hasClass('smaller-table-font'))
                      { $('#custom_list_details').removeClass('compact smaller-table-font')}
                    else { $('#custom_list_details').addClass('compact smaller-table-font')}


                }
            }

   ],
   "columnDefs": [
   {
         'targets': 0,
         'checkboxes': {
            'selectRow': true
         }
          
      }    
      
  ],
  "autoWidth":false,
 "columns": $columns,
 "pageLength": $user_profile_data.table_length,
 'lengthMenu': [
 [10, 50,100, -1],
 [10, 50,100, "All"]
 ],
   "columnDefs": [
   {
         'targets': 0,
         'className': 'center-text',
         'checkboxes': {
            'selectRow': true
         }
      }
  ],
  initComplete: function ()
 {


$("th[data-column-index='1']").css("background-color","white")
$("th[data-column-index='0']").css("background-color","white") 


  var api = this.api();
   api
                .columns()
                .eq(0)
                .each(function (colIdx) {
                  if (colIdx > 0) {
                    // Set the header cell to contain the input element
                    var cell = $('.head_filters th').eq(
                        $(api.column(colIdx).header()).index()
                    );
                                       
                    $(cell).html('<input class="form-control" style="width:100%" type="text" placeholder="" />');
 
                    // On every keypress in this input
                    $(
                        'input',
                        $('.head_filters th').eq($(api.column(colIdx).header()).index())
                    )
                        .off('keyup change')
                        .on('keyup change', function (e) {
                            e.stopPropagation();
 
                            // Get the search value
                            $(this).attr('title', $(this).val());
                            var regexr = '({search})'; //$(this).parents('th').find('select').val();
 
                            var cursorPosition = this.selectionStart;
                            // Search the column for that value
                            api
                                .column(colIdx)
                                .search(
                                    this.value != ''
                                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                                        : '',
                                    this.value != '',
                                    this.value == ''
                                )
                                .draw();
 
                            $(this)
                                .focus()[0]
                                .setSelectionRange(cursorPosition, cursorPosition);
                        });
                      }
                      else {
                         var cell = $('.head_filters th').eq(
                          $(api.column(colIdx).header()).index()
                        );
                         $(cell).html('');

                      }
                });
   
    custom_list_details_table.columns.adjust() 
   //column search end   
  

     
    }
          });

here is fiddle with the issue, input search is not fixed这是摆弄问题,输入搜索不固定

According to DataTables docs about FixedColums :根据有关FixedColums的 DataTables 文档

Additional complexity额外的复杂性

It is important to state up front that utilising FixedColumns in your DataTable can significantly increase the complexity of the table and its use should not be undertaken lightly, particularly for complex tables.重要的是 state 预先在 DataTable 中使用 FixedColumns 会显着增加表的复杂性,不应轻易使用它,尤其是对于复杂表。

Based on that, I don't really know if it's possible to create a second header row and make it FixedColumns compliant , with the normal initialization options.基于此,我真的不知道是否可以使用正常的初始化选项创建第二个 header 行并使其符合FixedColumns 标准

In Datatables' forum there's a question (a bit old indeed, made in 2016) about a problem with FixedColumns extension and multiple header rows, where the DataTable developer answers :在 Datatables 的论坛中,有一个问题(确实有点老,2016 年提出)关于 FixedColumns 扩展和多个header行的问题, DataTable 开发人员在其中回答

This ultimately is due to a limitation in DataTables in that you cannot construct complex headers using its initialisation options .这最终是由于 DataTables 的限制,因为您不能使用其初始化选项构造复杂的标头

Maybee this kind of issue is still here after 6 years? Maybee 这种问题在 6 年后仍然存在? Don't know:)不知道:)

That said, I managed to get it work with standard jQuery's DOM manipulation.也就是说,我设法让它与标准 jQuery 的 DOM 操作一起工作。

I added this drawCallback() in the initialization options, to have column widths recalculated on each draw:我在初始化选项中添加了这个drawCallback() ,以便在每次绘制时重新计算列宽:

drawCallback: function () {
    var api = this.api();
    api.columns.adjust();
}

After the table initialization and before the end of $(document).ready() I added a function to get the left CSS value from the fixed cells of the first header row and pass them to the corresponding cells in the second header row:在表初始化之后和$(document).ready()结束之前,我添加了一个 function 以从第一个 header 行的固定单元格中获取left的 CSS 值,并将它们传递给第二个 header 行中的相应单元格:

function cssAdjust(table) {
    // get the table header
    const header = table.table().header();

    // get the 'left' CSS declaration value for first_row-first_column 'th' cell
    const col1_CSS_left = $(header)
        .find('tr')
        .eq(0)      // first row
        .find('th')
        .eq(0)      // first column 
        .css('left');

    // apply the found value to the second_row-first_column 'th' cell
    $(header)
        .find('tr')
        .eq(1)      // second row
        .find('th')
        .eq(0)      // first column
        .css({ left: col1_CSS_left, position: 'sticky' });
    
    // get the 'left' CSS declaration value for first_row-second_column 'th' cell    
    const col2_CSS_left = $(header)
        .find('tr')
        .eq(0)      // first row
        .find('th')
        .eq(1)      // second column
        .css('left');
    
    // apply the found value to the second_row-second_column 'th' cell
    $(header)
        .find('tr')
        .eq(1)      // second row
        .find('th')
        .eq(1)      // second column
        .css({ left: col2_CSS_left, position: 'sticky' });

    table.draw(); // redraw the table
}

After that, always before the end of $(document).ready() , I added a window.resize listener, to avoid messing up widths of columns if the window is resized:在那之后,总是在$(document).ready()结束之前,我添加了一个window.resize侦听器,以避免在调整 window 的大小时弄乱列的宽度:

// add eventListener to window resize
window.addEventListener('resize', function () {
    cssAdjust(custom_list_details_table);
});

cssAdjust(custom_list_details_table); // <= I immediately call the function to have the fixed double header also in the first table draw;

Here is a codepen with the code: https://codepen.io/cheesyman/pen/NWXXdPO这是一个代码笔: https ://codepen.io/cheesyman/pen/NWXXdPO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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