原生JS table超过高度可滚动 - 附完整示例

在前端的学习中,使用原生JS的table是很常见的,故在此记录

效果

一、HTML

<div class="content">
  <div class="table">
    <table>
      <thead>
        <tr>
          <th class="w-150">Header 1</th>
          <th>Header 2</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="w-150">Row 1 Data 1</td>
          <td>Row 1 Data 2</td>
        </tr>
        <tr>
          <td class="w-150">Row 2 Data 1</td>
          <td>Row 2 Data 2</td>
        </tr>
        <tr>
          <td class="w-150">Row 3 Data 1</td>
          <td>Row 3 Data 2</td>
        </tr>
        <tr>
          <td class="w-150">Row 4 Data 1</td>
          <td>Row 4 Data 2</td>
        </tr>
        <tr>
          <td class="w-150">Row 5 Data 1</td>
          <td>Row 5 Data 2</td>
        </tr>
        <tr>
          <td class="w-150">Row 6 Data 1</td>
          <td>Row 6 Data 2</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

二、CSS

       1、给容器设置一个固定的宽高,并设置对齐方式,方便演示内容超出高度可滚动显示

        2、给td设置宽度,方便表头与内容对齐,需要注意表头的td和表体的td的宽度要一致,否则会出现错位的情况,这里为了方便都是设置的固定宽度,可根据实际情况使用百分比或者vw

.content {
  width: 300px;
  text-align: left;
}

.table {
  height: 100px;
  overflow-y: scroll;
}

.w-150 {
  width: 150px;
}

.content th, 
.content td {
  border-bottom: 1px solid #ebeef5;
}

三、完整示例

<template>
  <div class="content">
    <div class="table">
      <table>
        <thead>
          <tr>
            <th class="w-150">Header 1</th>
            <th>Header 2</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td class="w-150">Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
          </tr>
          <tr>
            <td class="w-150">Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
          </tr>
          <tr>
            <td class="w-150">Row 3 Data 1</td>
            <td>Row 3 Data 2</td>
          </tr>
          <tr>
            <td class="w-150">Row 4 Data 1</td>
            <td>Row 4 Data 2</td>
          </tr>
          <tr>
            <td class="w-150">Row 5 Data 1</td>
            <td>Row 5 Data 2</td>
          </tr>
          <tr>
            <td class="w-150">Row 6 Data 1</td>
            <td>Row 6 Data 2</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
</script>

<style scoped>
.content {
  width: 300px;
  text-align: left;
}

.table {
  height: 100px;
  overflow-y: scroll;
}

.w-150 {
  width: 150px;
}

.content th, 
.content td {
  border-bottom: 1px solid #ebeef5;
}
</style>

  欢迎扫描下方二维码关注VX公众号

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值