我有一个想法是制作表格的粘性标题,我尝试过使用position:sticky。它的 在Chrome上运行正常,但Firefox和IE无法正常工作。下面是我的CSS
.myTable--mof thead th {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index:100;
}
答案 0 :(得分:0)
position:sticky
。 '为什么'我不知道..未来是否会得到支持?我当然希望如此!
我最近写了这个jQuery解决方案。它适用于具有简单标题的简单表。 Does not look for colspans or multiple rows in thead!
之前我尝试了一些插件,但他们都听了滚动事件,它会在某些浏览器中抛出警报。在某些情况下,它们会引起闪烁/跳跃,并且在击中位置时会出现延迟。
将position:sticky
用于其他元素并更喜欢这些过渡,我想出了以下代码。
jQuery.fn.stickTableHeaders = function() {
return this.each(function()
{
var table = $(this),
header = table.find('thead'),
sticked = $('<table></table>').addClass('table').append(header.clone()); // Needs to be wrapped in new table since table child elements can't be sticky? (FF)
sticked.find('th').css({ // You'll have to copy the original thead (th's) CSS manualy
'backgroundColor': '#DEE5EA',
'color': '#606060',
'padding':'8px',
'color':'#606060'
}).removeAttr('width'); // And remove the width attr from the clone th's since we'll be setting them again later
sticked.find('th:not(:last-child)').css({ // More CSS
'borderRight': '1px solid #ddd'
});
sticked.find('a').css({ // More CSS
'color':'#606060'
});
// I tried different things, most of the original th's should have a width attribute set (not in CSS and avoid percent) for best results
$(window).resize(function() {
sticked.width(table.width());
sticked.find('th').each(function() {
var headerTH = header.find('th').eq($(this).index());
if(headerTH.is('[width]') || headerTH.is(':first-child') || headerTH.is(':last-child')) { // First and last th are allready calculated by another function in my app. See what suits for you here...
$(this).width(header.find('th').eq($(this).index()).width());
}
else {
var cellWidth = header.find('th').eq($(this).index()).width(true),
tableWidth = table.width(true),
percent = 100*(cellWidth/tableWidth);
$(this).css({'width':percent+'%'});
}
});
// We keep the original thead to avoid table collapsing, we just slide the whole table up.
table.css({
'marginTop':-header.height()
});
}).trigger('resize');
// Apply stickyness
sticked.css({
'display':'table',
'position':'sticky',
'top':$('#header-menu').height(), // My sticky nav is my top position, adjust this to your needs
'zIndex':'10'
});
// Insert clone before original table
$(this).before(sticked);
});
};
现在我只是在每个页面加载时使用它:
$("table").stickTableHeaders();
您可能希望从上面的选择器中过滤掉嵌套表...
希望这有助于某人。