2014-09-04 74 views
0

我正在嘗試製作粘貼表格標題。這是我迄今爲止所需要的一個例子。如何使表格標題粘貼標題?

這是我從其他人那裏找到的代碼。

function makeTableHeadersSticky(tableId) { 
var thArr = $(tableId + " th"); 

var thWidthsArr = []; 
$(tableId + " th").each(function(){ 
    thWidthsArr.push($(this).css("width")); 
}); 

var pos = $(tableId).offset(); 

var thTop = pos.top + "px"; 

var count = 0; 
$(tableId + " tr:first-child > th").each(function(){ 
    $(this).css("width", thWidthsArr[count]); 
    count++; 
}); 
count = 0; 

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

$(window).scroll(function(){ 
    if($(window).scrollTop() > pos.top) { 
     $(tableId + " tr:first-child").css("position", "fixed"); 
     $(tableId + " tr:first-child").css("top", "0px"); 
    } else { 
     $(tableId + " tr:first-child").css("position", "relative"); 
     $(tableId + " tr:first-child").css("top", thTop); 
    } 
}); 
console.log(thTop); 

} 

makeTableHeadersSticky("#myTable"); 

在這裏你可以看到我想要實現一個DEMO JSFiddle

+0

你有一個工作的例子。看起來你已經對你的問題有了答案。你還希望到達這裏? – 2014-09-04 15:28:34

回答

0

你可以使用CSS來修復標題到頂部,然後給容器保證金在頂部溢出停止:

http://jsfiddle.net/n9wac1x6/5/

header { 
    width: 100%; 
    background-color: #fff; 
    height: 50px; 
    position: fixed; 
    top:0; 
    left: 0; 
} 

h1 { 
    position: absolute; 
    left: 5px; 
    top 2px; 
    padding: 0; 
    margin: 0; 
} 

.container { 
    margin-top: 50px; 
}