したがって、いくつかの行と列を持ついくつかのテーブルがあります。情報が膨大なので、スクロールするときにテーブルヘッダーを一番上に固定したいと思います。1つのヘッダーが来ると、前のヘッダーは非表示になり、現在のヘッダーは固定されたままになります。
これは私がこれまでに持っているjsコードです:
function makeTableHeadersSticky(tableId) {
var thArr = $(tableId + " th");
var thWidthsArr = [];
var calcWidth = 0;
$(tableId + " th").each(function(){
calcWidth = $(this).css("width");
thWidthsArr.push(calcWidth);
});
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() {
//var firstRow = $(tableId + " tr:first-child").offset();
var lastRow = $(tableId + " tr:last-child").offset();
var w = $(window);
//console.log("(first,last): ("+(firstRow.top-w.scrollTop())+","+(lastRow.top-w.scrollTop())+")");
if(($(window).scrollTop() > pos.top) && (lastRow.top-w.scrollTop() >= 0)) {
$(tableId + " tr:first-child").css("position", "fixed");
$(tableId + " tr:first-child").css("top", "0px");
$(tableId + " tr:first-child").css("left", "9px");
} else {
$(tableId + " tr:first-child").css("position", "static");
$(tableId + " tr:first-child").css("top", thTop);
}
});
}
makeTableHeadersSticky("#myTable");
私のコードを見ると、テーブルの位置とテーブルの最後の行を操作して、テーブルがどこにあるかを確認しました。このようにして、ヘッダーの位置を固定または静的に設定できます。
これが私のjsfiddleです
ここではすべてが正常に機能します。makeTableHeadersSticky
2番目のテーブルの関数を呼び出すのを省略しました:
makeTableHeadersSticky("#myTable2");
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加