我正試圖在滾動時將表頭粘到頂部。滾動時粘滯表頭不保持寬度
我使用的是這裏提供的解決方案:css-tricks.com/persistent-headers/。
但是,當我嘗試使用它時,表頭不保持其寬度。
function UpdateTableHeaders() {
$(".persist-area").each(function() {
var el = $(this),
offset = el.offset(),
scrollTop = $(window).scrollTop(),
floatingHeader = $(".floatingHeader", this)
if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
floatingHeader.css({
"visibility": "visible"
});
} else {
floatingHeader.css({
"visibility": "hidden"
});
};
});
}
$(function() {
var clonedHeaderRow;
$(".persist-area").each(function() {
clonedHeaderRow = $(".persist-header", this);
clonedHeaderRow
.before(clonedHeaderRow.clone())
.css("width", clonedHeaderRow.width())
.addClass("floatingHeader");
});
$(window)
.scroll(UpdateTableHeaders)
.trigger("scroll");
});
.floatingHeader {
position: fixed;
top: 0;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table class="persist-area">
<tr class="persist-header">
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
如何讓我的表列排列,並期待自然?
任何幫助將不勝感激!
Thanks!沒有意識到它的位置:固定的問題。正在寫js和jquery的行試圖修復它! – Vera
嗯,滾動粘滯表格標題後,不改變和改變寬度,當我改變窗口的大小,像表一樣。任何想法? – Vera
你可以嘗試給它'寬度:100%;',並看看是否有效(你將不得不刪除你設置的寬度在JavaScript壽,在javascript中設置的樣式將是一種內聯樣式,並將優先你在css中寫的那個)。如果這不起作用,你可能需要創建一個'$(窗口)。resize(function(){})'事件並更新固定標頭寬度以匹配,就像你當前在滾動 – zgood