jQuery DataTables 固定标题与宽表中的列不对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13178039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:22:54  来源:igfitidea点击:

DataTables fixed headers misaligned with columns in wide tables

jquerydatatables

提问by bPratik

Problem

问题

When using the sScrollX, sScrollXInnerand/or sScrollYto achieve a fixed header table with its inner content scrolling, the headers of the table go out of alignment with the rest of the body in Chrome and IE. Firefox, on the other hand, displays them perfectly.

当使用sScrollX,sScrollXInner和/或sScrollY实现固定的标题表及其内部内容滚动时,表格的标题与 Chrome 和 IE 中的正文的其余部分不对齐。另一方面,Firefox 完美地显示了它们。

Using the version 1.9.4, as far as I can tell, this issue only occurs when there is a lot of data with fluctuating widths, and with words that are very long/unwrappable combined in the same columns as small ones. Also, the table in question needs to be fairly wide.

使用 1.9.4 版本,据我所知,这个问题只发生在有大量宽度波动的数据,并且非常长/不可包装的单词与小单词组合在同一列中时。此外,有问题的表格需要相当宽。

All these factors are demonstrated in this fiddle:

所有这些因素都在这个小提琴中得到了证明:

Output

输出

Chrome:
Chrome Screenshot

铬合金:
Chrome 截图

IE:
IE9 Screenshot

IE:
IE9 截图

Firefox
Firefox Screenshot

火狐
火狐截图

Suggested Solutions

建议的解决方案

These solutions have been suggested before but have had no effecton my implementation. Owing to some of these suggestions, I setup a clean plain vanilla demo as I wanted to ensure that no other code was contributing to this effect.

这些解决方案之前已经提出过,但对我的实施没有影响。由于这些建议中的一些,我设置了一个干净的普通演示,因为我想确保没有其他代码对这种效果有贡献。

  • turn-off/remove all my css
  • setTimeout( function () { oTable.fnAdjustColumnSizing(); }, 10 );
  • calling oTable.fnFilter( "x",0 )and oTable.fnFilter( "",0 )in that order
  • "sScrollXInner": "100%"
  • get rid of all widths
  • 关闭/删除我所有的 css
  • setTimeout( function () { oTable.fnAdjustColumnSizing(); }, 10 );
  • 调用oTable.fnFilter( "x",0 )并按oTable.fnFilter( "",0 )该顺序
  • "sScrollXInner": "100%"
  • 摆脱所有宽度

The only solution that I found to the misaligned headers was taking out sScrollXand sScrollY, but this can't be counted as a solution as you lose the fixed header/inner content scrolling functionality. So sadly it's a temporary hack, not a fix!

我发现对未对齐标题的唯一解决方案是取出sScrollXand sScrollY,但这不能算作解决方案,因为您失去了固定的标题/内部内容滚动功能。很遗憾,这是一个临时的黑客攻击,而不是修复!

Note

笔记

To edit/play with the latest fiddle.

编辑/播放最新的小提琴

I have tried various combinations which can be observed in the revision history of the fiddle by using the link http://jsfiddle.net/pratik136/etL73/#REV#where 1 <= #REV# <= 12

我尝试了各种组合,可以通过使用链接http://jsfiddle.net/pratik136/etL73/#REV#在小提琴的修订历史中观察到1 <= #REV# <= 12

History

历史

StackO
This question has been asked before: jQuery Datatables Header Misaligned With Vertical Scrolling
but the vital difference is that the OP of that question mentioned that they were able to fix the issue if all CSS was removed, which is untrue in my case, and I have tried a few permutations, thus thought the question worthy of a repost.

StackO
这个问题之前曾被问过:jQuery Datatables Header Misaligned With Vertical Scrolling
但重要的区别是该问题的 OP 提到如果删除所有 CSS,他们能够解决这个问题,这在我的情况下是不正确的,我尝试了一些排列,因此认为这个问题值得转发。

External
This issue has also been flagged on the DataTables forum:

外部
此问题也已在 DataTables 论坛上标记:

This issue has driven me nuts! Please contribute your thoughts!

这个问题把我逼疯了!请贡献你的想法!

采纳答案by Ruslans Uralovs

EDIT: See the latest Fiddlewith "fixed header":

编辑:查看带有“固定标题”的最新小提琴



The Fiddle.

小提琴

One of the solutions is to implement scrolling yourself instead of letting DataTables plugin do it for you.

解决方案之一是自己实现滚动,而不是让 DataTables 插件为您完成。

I've taken your example and commented out sScrollX option. When this option is not present DataTables plugin will simply put your table as is into a container div. This table will stretch out of the screen, therefore, to fix that we can put it into a div with required width and an overflow property set - this is exactly what the last jQuery statement does - it wraps existing table into a 300px wide div. You probably will not need to set the width on the wrapping div at all (300px in this example), I have it here so that clipping effect is easily visible. And be nice, don't forget to replace that inline style with a class.

我已经拿你的例子和注释掉了 sScrollX 选项。当此选项不存在时,DataTables 插件将简单地将您的表按原样放入容器 div 中。该表将伸出屏幕,因此,为了解决这个问题,我们可以将其放入具有所需宽度和溢出属性集的 div - 这正是最后一个 jQuery 语句所做的 - 它将现有表包装到一个 300px 宽的 div 中。您可能根本不需要在环绕 div 上设置宽度(在此示例中为 300px),我在这里提供了它,以便很容易看到剪辑效果。并且保持良好,不要忘记用类替换内联样式。

$(document).ready(function() {
var stdTable1 = $(".standard-grid1").dataTable({
    "iDisplayLength": -1,
    "bPaginate": true,
    "iCookieDuration": 60,
    "bStateSave": false,
    "bAutoWidth": false,
    //true
    "bScrollAutoCss": true,
    "bProcessing": true,
    "bRetrieve": true,
    "bJQueryUI": true,
    //"sDom": 't',
    "sDom": '<"H"CTrf>t<"F"lip>',
    "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
    //"sScrollY": "500px",
    //"sScrollX": "100%",
    "sScrollXInner": "110%",
    "fnInitComplete": function() {
        this.css("visibility", "visible");
    }
});

var tableId = 'PeopleIndexTable';
$('<div style="width: 300px; overflow: auto"></div>').append($('#' + tableId)).insertAfter($('#' + tableId + '_wrapper div').first())});

回答by Draykos

The following is a way to achieve a fixed header table, I don't know if it will be enough for your purpose. Changes are:

下面是一种实现固定头表的方法,不知道对你的目的是否足够。变化是:

  1. use "bScrollCollapse" instead of "sScrollXInner"
  2. don't use fieldset to wrap table
  3. add a "div.box" css class
  1. 使用“bScrollCollapse”而不是“sScrollXInner”
  2. 不要使用字段集来包装表格
  3. 添加一个“div.box”css类

It seems fully working on my local machine, but it's not fully working using Fiddle. It seems that Fiddle adds a css file (normalize.css) that in some way broke the plugin css (quite sure I can make fully working also in Fiddle adding some css clear rules, but not have time to investigate further now)

它似乎在我的本地机器上完全正常工作,但使用 Fiddle 并不能完全正常工作。似乎 Fiddle 添加了一个 css 文件(normalize.css),该文件以某种方式破坏了插件 css(很确定我也可以在 Fiddle 中完全工作,添加一些 css 明确规则,但现在没有时间进一步调查)

My working code snippet is below. Hope this can help.

我的工作代码片段如下。希望这能有所帮助。

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
  <script type='text/javascript' src="http://datatables.net/release-datatables/media/js/jquery.dataTables.min.js"></script>

 <style type='text/css'>
       div.box {
       height: 100px;
       padding: 10px;
       overflow: auto;
       border: 1px solid #8080FF;
       background-color: #E5E5FF;
   }

  .standard-grid1, .standard-grid1 td, .standard-grid1 th {
    border: solid black thin;
   }
</style>

<script type='text/javascript'> 
$(window).load(function(){
$(document).ready(function() {
    var stdTable1 = $(".standard-grid1").dataTable({
        "iDisplayLength": -1,
        "bPaginate": true,
        "iCookieDuration": 60,
        "bStateSave": false,
        "bAutoWidth": false,
        //true
        "bScrollAutoCss": true,
        "bProcessing": true,
        "bRetrieve": true,
        "bJQueryUI": true,
        "sDom": '<"H"CTrf>t<"F"lip>',
        "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
        "sScrollX": "100%",
        //"sScrollXInner": "110%",
        "bScrollCollapse": true,
        "fnInitComplete": function() {
            this.css("visibility", "visible");
        }
    });
});
});

</script>


</head>
<body>
<div>
    <table class="standard-grid1 full-width content-scrollable" id="PeopleIndexTable">
        <thead>
          <!-- put your table header HTML here -->
       </thead>
       <tbody>
          <!-- put your table body HTML here -->
        </tbody>
    </table>
</div>
</body>
</html>

回答by Mohanrajan

I am having the same issue on IE9.

我在 IE9 上遇到了同样的问题。

I will just use a RegExp to strip all the white spaces before writing the HTML to the page.

在将 HTML 写入页面之前,我将使用 RegExp 去除所有空格。

var Tables=$('##table_ID').html();
var expr = new RegExp('>[ \t\r\n\v\f]*<', 'g');
Tables= Tables.replace(expr, '><');
$('##table_ID').html(Tables);
oTable = $('##table_ID').dataTable( {
  "bPaginate": false,
  "bLengthChange": false,
  "bFilter": false,
  "bSort": true,
  "bInfo": true,
  "bAutoWidth": false,
  "sScrollY": ($(window).height() - 320),
  "sScrollX": "100%",
  "iDisplayLength":-1,
  "sDom": 'rt<"bottom"i flp>'
} );

回答by Ben Leitner

Adding these two lines fixed this problem for me

添加这两行为我解决了这个问题

"responsive": true,
"bAutoWidth": true

There is now a responsive plugin available: https://datatables.net/extensions/responsive/. However, in my experience I have found that there are still a few bugs. It's still the best solution I've found so far.

现在有一个响应式插件可用:https: //datatables.net/extensions/responsive/。但是,根据我的经验,我发现仍然存在一些错误。它仍然是我迄今为止找到的最好的解决方案。

回答by Vishnoo Rath

The code below worked. Corrected the issue on I.E 9.0 atleast. Hope this helps

下面的代码有效。至少更正了 IE 9.0 上的问题。希望这可以帮助

var oTable =  $('#tblList').dataTable({
    "sScrollY": "320px",
    "bScrollCollapse": true,
    });

    setTimeout(function(){
        oTable.fnAdjustColumnSizing();
    },10);

回答by Earl

I had the same problem and this code solves it. I got this solution from this article but I had to adjust the time on the interval for it to work.

我有同样的问题,这段代码解决了它。我从这篇文章中得到了这个解决方案,但我必须调整时间间隔才能让它工作。

setTimeout(function(){
        oTable.fnAdjustColumnSizing();
},50);

回答by Divyanshu Rawat

Trigger DataTable search function after initializing DataTable with a blank string in it. It will automatically adjust misalignment of theadwith tbody.

使用空字符串初始化DataTable 后触发DataTable 搜索功能。它会自动调整thead与 的错位tbody

$( document ).ready(function()
{

    $('#monitor_data_voyage').DataTable( {
        scrollY:150,
        bSort:false,
        bPaginate:false,
        sScrollX: "100%",
        scrollX: true,
    } );

    setTimeout( function(){
       $('#monitor_data_voyage').DataTable().search( '' ).draw();
    }, 10 );

});

回答by Sam

For bootstrap users, this fixed it for me:

对于引导用户,这为我修复了它:

   $($.fn.dataTable.tables(true)).DataTable()
      .columns.adjust()
      .fixedColumns().relayout();

See article here

这里的文章

回答by Ah Hui

try this, the following code solved my problem

试试这个,下面的代码解决了我的问题

table.dataTable tbody th,table.dataTable tbody td 
{
     white-space: nowrap;
} 

for more information pls refer Here.

有关更多信息,请参阅此处

回答by BulletVictim

I know there has been an answer flagged already, but for someone with similar problems that the above does not work for. I'm using it in conjunction with bootstrap theme.

我知道已经标记了一个答案,但是对于有类似问题但上述方法不起作用的人。我将它与引导程序主题结合使用。

There is a line that can be altered in the dataTables.fixedHeader.js file. the default layout of the function looks as follows.

dataTables.fixedHeader.js 文件中有一行可以更改。该函数的默认布局如下所示。

    _matchWidths: function (from, to) {
        var get = function (name) {
            return $(name, from)
                .map(function () {
                    return $(this).width();
                }).toArray();
        };

        var set = function (name, toWidths) {
            $(name, to).each(function (i) {
                $(this).css({
                    width: toWidths[i],
                    minWidth: toWidths[i]
                });
            });
        };

        var thWidths = get('th');
        var tdWidths = get('td');

        set('th', thWidths);
        set('td', tdWidths);
    },

change the

改变

    return $(this).width();

to

    return $(this).outerWidth();

outerWidth() is a function that is contained in jquery.dimensions.js if you are usingg a newer version of jquery. ie. jquery-3.1.1.js

如果您使用较新版本的 jquery,outerWidth() 是一个包含在 jquery.dimensions.js 中的函数。IE。jquery-3.1.1.js

what the above function does is it maps the th of the original table, then applies them to the "cloned" table(fixed header). in my case they were always off by about 5px to 8px when misaligned. Most probably not the best fix out there but provides a solution to all other tables in the solution without having to specify it per table declaration. It has only been tested in Chrome so far, but it should provide an adjudicate solution on all browsers.

上面函数的作用是映射原始表的 th,然后将它们应用于“克隆”表(固定标题)。在我的情况下,它们在未对齐时总是偏离大约 5px 到 8px。很可能不是最好的解决方案,但为解决方案中的所有其他表提供了解决方案,而不必为每个表声明指定它。到目前为止,它仅在 Chrome 中进行了测试,但它应该在所有浏览器上提供裁决解决方案。