如何设置固定表标题的克隆tr的宽度

时间:2013-12-18 11:24:48

标签: jquery html css

最终目标是创建“粘性”列标题,一旦下一个标题到达窗口顶部,它就会移开。 我已经在网上看了一下,发现至少有4或5个插件,这些插件似乎都是基于thead而不是tr th

到目前为止,我有一个大表,它被分成几个部分,每个部分都有一行th。 我使用jQuery将每个tr元素克隆到一个位于窗口顶部的新表中。

接下来,我修复了每个tr的位置,以便每行堆叠。我遇到的问题是设置宽度。我已经能够设置tr的内容,但是当我尝试根据原始内容获取并设置克隆的th时,它只是不起作用。

有很多代码可以看到这个工作,我将包含jQuery,因为这是我需要帮助的,这里还有一个jsfiddle:http://jsfiddle.net/wf_4/NQNt7/

(function () {
    var tableWrapper = $('<div />').attr({ id: 'fakeTableWrapper' }),
        newTable = $('<table />').attr({ id: 'fakeTable', 'class': 'rpt' }).css({ 'table-layout': 'fixed' });

    $('#page').prepend(tableWrapper) 
    $('#fakeTableWrapper').prepend(newTable);

})();

 $('tr.tabHead').each(function () {
    var $this = $(this),
        w = $this.innerWidth() + 'px',
        copy = $this.clone(),

        $tableBodyCell = $('tr.tabHead:first td'),
        $headerCell = copy.children('th');

    copy.removeAttr('class');
    copy.children('th').removeAttr('data-coltype');
    copy.children('th').removeAttr('data-col');
    copy.children('th').removeAttr('class');
    copy.children('th').removeAttr('style');

    //THIS IS WHAT IS NOT WORKING, TRYING TO SET THE CLONE TH
    $tableBodyCell.each(function (index) {
        copy.children('th').removeAttr('style');
        $headerCell.eq(index).width($(this).width());
    });     

    $('#fakeTable tr').css({ 'width': w });

        $('#fakeTable').append(copy);
})

1 个答案:

答案 0 :(得分:1)

如果我理解你想要实现的目标,那看起来它只是一个选择器问题。没有td trtabHead作为其父级,因此代码未进入$tableBodyCell.each循环。

替换td

$tableBodyCell = $('tr.tabHead:first td')

使用th

$tableBodyCell = $('tr.tabHead:first th')

演示:http://jsfiddle.net/NQNt7/5/

相关问题