【发布时间】:2015-02-17 12:18:32
【问题描述】:
我正在使用这个 jQuery 使表格标题变得粘滞。
(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);
这可行,但我使用 CSS 更新了表格的外观并添加了 border-collapse : collapse
这导致标题大小在浮动时发生变化。
任何人有任何想法如何让大小在浮动时保持为原始标题?
我创建了一个小提琴 here.. 但由于某种原因它没有运行。
【问题讨论】: