Question

I have a table and I want to make the first row "auto fixed"(that means when scroll down it is fixed at top, while if not scroll down, it is not fixed). Here is code: ```

<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>

When I scroll down, the first row is fixed at top but looks its width changed. I use Chrome element inspector and find the tr's width is same this other rows, but each th's width is changed. Is there any way to make sub-elements(here are those ths)'s width and height not change?

Was it helpful?

Solution 2

I just tried this method, store each sub-element's default width and height and set them to default width and height when scroll down. It works!

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 {
  }
});

OTHER TIPS

I would use a jQuery plugin like this one - https://github.com/markmalek/Fixed-Header-Table

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top