使用HTML冻结表头

时间:2018-08-29 16:01:29

标签: javascript jquery html

我有一个几乎有无限行的表,我需要使表内容滚动(tabebody),同时保持标题冻结(保持标题不可滚动)

我有想要的代码,

<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>

<div align="center" id="id1" style="height: 240px;overflow:auto">
<table id="tbl" class="class1" align="center" width="100%" border="1">
    <thead>
        <tr>
            <th class="first"><input type="checkbox" id="select-all"></th>
            <th class="second">Edit</th>
            <th class="third">&nbsp;</th>
            <th class="fourth">Timestamp</th>
        </tr>
    </thead>
    <tr>
        <td class="first"><input class="selects" type="checkbox" value="A1" id="r0"></td>
        <td class="second"><a target="_blank" href="www.uitshj.org?show=A1">1</a></td>
        <td class="third"><a href="#" class='option' id='option_1' >Option 1</a></td>
        <td class="fourth">2018-08-26T10:38:01.602Z</td>
    </tr>
    <tr>
        <td class="first"><input class="selects" type="checkbox" value="B1" id="r1"></td>
        <td class="second"><a target="_blank" href="www.uitshj.org?show=B1">2</a></td>
        <td class="third"><a href="#" class='option' id='option_2' >Option 2</a></td>
        <td class="fourth">2018-08-26T10:23:42.119Z</td>
    </tr>
    <tr>
        <td class="first"><input class="selects" type="checkbox" value="C1" id="r2"></td>
        <td class="second"><a target="_blank" href="www.uitshj.org?show=C1">3</a></td>
        <td class="third"><a href="#" class='option' id='option_3'>Option 3</a></td>
        <td class="fourth">2018-08-26T01:05:00.171Z</td>
    </tr>
</table>
</div>

<script>

var myJson = {
  option_1: {'name': 'Clark', age:'39', address:'Washington D.C.'},
  option_2: {'name': 'Bob', age:'26', address:'Texas'},
  option_3: {'name': 'Angelina', age:'31', address:'Ohio'}
}

$(document).ready(function(){
  $('.option').click(function(e){
    e.preventDefault();
    id = $(this).attr('id');
    values = myJson[id];

    parent = $(this).parent('td')
    existing_content = parent.find('.option_content')
    if( existing_content.length ){ //if content exists, remove it
      existing_content.remove()
    } else { //else add the content
      content = "<div class='option_content'>" + values.name + "<br>" + values.age + "<br>" + values.address + "</div>";
      $(this).after(content)
    }
  })
})
</script>

如何保持表头不可滚动?

1 个答案:

答案 0 :(得分:1)

所以,换句话说,假设您已经掌握了所有类的单元格的宽度(第一,第二,第三,第四)。您需要做的就是将这两行代码添加到样式部分:

<style type='text/css'>
  .class1 > thead { display: table; }
  .class1 > tbody { display: block; overflow: scroll; height: 240px; }
</style>

它应该工作。