0

I'm using this jQuery to make table headers sticky.

(function($)
{
    $.fn.sticky = function()
    {
        var tableId = this;
        var tableWidth = $(tableId).width();
        var tableHeight = $(tableId).height();
        var thHeight = $(tableId).find("th:first").parent().height();

        var thWidthsArr = [];
        $(tableId).find("th").each(function(){
            thWidthsArr.push($(this).css("width"));
        });
        var pos = $(tableId).offset();
        var thTop = pos.top + "px";
        var thLeft = pos.left;

        var firstRow = "tr:first-child";

        var hasTHead = $(tableId).find("thead").length;
        if(hasTHead) firstRow = "thead tr:first-child";

        var count = 0;
        $(tableId).find(firstRow + ">th").each(function(){
            $(this).css("width", thWidthsArr[count]);
            count++;
        });
        count = 0;

        var lastRow = "tr:last-child";
        $(tableId).find(lastRow + ">td").each(function(){
            $(this).css("width", thWidthsArr[count]);
            count++;
        });


        $(window).scroll(function(){
            if($(window).scrollTop() > pos.top && $(window).scrollTop() < pos.top + tableHeight - thHeight)
            {
                $(tableId).find(firstRow).css("width", tableWidth+"px");
                $(tableId).find(lastRow).css("width", tableWidth+"px");
                $(tableId).find(firstRow).css("position", "absolute");
                $(tableId).find(firstRow).css("top", ($("body")[0].scrollTop - 2) + "px");
                $(tableId).find(firstRow).css("left", thLeft+ "px");
            }
            else
            {
                $(tableId).find(firstRow).css("position", "relative");
                $(tableId).find(firstRow).css("top", thTop);
            }
        });

    }
})(jQuery);

This works, but I've updated the look of my table using CSS and added border-collapse : collapse

This has resulted in the header size changing as it floats.

Anyone have any ideas how I can get the size to stay as the original header when it's floating?

I've created a fiddle here.. but for some reason it's not running.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rocket
  • 1,065
  • 2
  • 21
  • 44

1 Answers1

1

After my modifications: http://jsfiddle.net/8ntdmpe7/1/

Set only width for cells (td and th), not tr. And all cells, not only first and last row.

Used outerWidth instead of width.

Changed box-sizing as below:

table, table * {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
mkutyba
  • 1,417
  • 1
  • 10
  • 26