У меня есть таблица, и я хочу сделать первую строку "автоматически фиксированной" (это означает, что при прокрутке вниз она фиксируется сверху, а если не прокручивается вниз, она не фиксируется). Вот код: '' '
<style type="text/css">
table {
background: yellow;
}
td {
width: 50px;
}
</style>
<table border="1">
<tr class="auto-header">
<th>123</th>
<th>123</th>
<th>123</th>
<th>123</th>
</tr>
<tr>
<td>123</td>
<td>123</td>
<td>123</td>
<td>123</td>
</tr>
... # many rows
</table>
<script type="text/javascript">
$(document).ready(function() {
$(".auto-header").each(function() {
var $this = $(this),
top = $this.offset().top,
left = $this.offset().left,
width = $this.width(),
height = $this.height;
console.log(width);
$(window).scroll(function() {
if($(window).scrollTop() >= top) {
$this.css({
position: "fixed",
top: 0,
left: left,
"z-index": 100,
width: width,
height: height
});
} else {
// to be implemented
}
});
});
});
</script>
Когда я прокручиваю вниз, первая строка фиксируется сверху, но выглядит измененной. Я использую Chrome элемент инспектора и найти tr
ширина же это остальные строки, но каждый th
ширины изменяется. Есть ли способ сделать субэлементы (вот эти th
s) ширина и высота не изменяются?
Я просто пробовал этот метод, сохранял каждую ширину и высоту каждого подэлемента по умолчанию и устанавливал их по умолчанию по ширине и высоте при прокрутке вниз. Оно работает!
var $this = $(this),
top = $this.offset().top,
left = $this.offset().left,
width = $this.width(),
height = $this.height(),
widthArr = [],
heightArr = [];
$this.find("*").each(function(i, e) {
widthArr.push($(this).width());
heightArr.push($(this).height());
});
$(window).scroll(function() {
if($(window).scrollTop() >= top) {
$this.css({
position: "fixed",
top: 0,
left: left,
"z-index": 100,
width: width,
height: height
});
$this.find("*").each(function(i, e) {
$(this).width(widthArr[i]);
$(this).height(heightArr[i]);
});
} else {
}
});
Я бы использовал плагин jQuery, подобный этому: https://github.com/markmalek/Fixed-Header-Table