表格thead固定位置与顶部栏

时间:2016-08-22 17:08:05

标签: javascript jquery html css html-table

我有一个顶部栏,我在滚动时将其设置为固定位置。 下面我有一张桌子。我希望一旦顶部栏设置为固定就修复该表的thead,并且表的行应该在thead后面滚动,如here

JS:

$(document).ready(function() {
  var fixmeTop = $(".fixme").offset().top;
  var countriesTableTop = $(".fixme").height() + 20; //20 is the margin
  $(window).scroll(function() {
    var currentScroll = $(window).scrollTop();
    if (currentScroll >= fixmeTop) {
      $(".fixme").css({"position": "fixed", "top": "0", "left": "0"});
      $(".countries-table thead").css({"position": "fixed", "top": countriesTableTop});
    } else {
      $(".fixme").css("position", "static");
      $(".countries-table thead").css("position", "static");
    }
  });
});

的CSS:

.fixme {
  width: 100%;
  margin-top: 0 !important;
  background-color: #000;
  z-index: 5000;
  margin-bottom: 20px;
}

.countries-table {
  width: 100%;
  background-color: silver;
}

.countries-table thead {
  font-weight: bold;
  z-index: 200
}

它适用于顶栏固定位置,但遗憾的是不适用于桌面。

查看我的jsfiddle

请注意,我没有限制桌面高度。这个想法是用户将始终看到thead。

1 个答案:

答案 0 :(得分:0)

试试这个

.fixme {
    width: 100%;
    margin-top: 0 !important;
    background-color: #000;
    z-index: 5000;
    margin-bottom: 20px;
}
.countries-table {
    width: 382px;
    background-color: silver;
    table-layout: fixed;
}
.countries-table thead tr {
    font-weight: bold;
    display: block;
    position: relative;
    background: #333;
    color: #fff;
    width: 383px;
}
.countries-table tbody {
    display: block;
    overflow: auto;
    width: 100%;
    height: 300px;
}
.countries-table thead tr td:nth-child(1),
.countries-table tbody tr td:nth-child(1) {
    padding: 4px;
    width: 190px;
}
.countries-table thead tr td:nth-child(2),
.countries-table tbody tr td:nth-child(2) {
    padding: 4px;
    width: 190px;
}
.countries-table tbody tr:nth-child(odd) {
    background: #f5f5f5;
}

CLICK HERE FOR DEMO

相关问题