前端实现表格列滑动固定以及边框问题

53 阅读2分钟
<table v-if="comStatus === 'normal'">
  <thead>
    <tr>
      <th class="th-1 sticky-column">人员</th>
      <th class="th-2">YTD增长率</th>
      <th class="th-3">YTD增长额</th>
      <th class="th-1" v-for="item in props.tableList?.months" :key="item">{{ item }}</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item, index) in props.tableList?.tableData" :key="item">
      <td class="sticky-column">{{ item.name }}</td>
      <td v-if="index === 0" class="rs" :rowspan="props.tableList?.tableData.length">
        <div class="echarts" :id="`echarts-${echartsId}`"></div>
      </td>
      <td>{{ item.ytdValue }}</td>
      <!-- 动态渲染每月数据 -->
      <td v-for="month in props.tableList?.months" :key="month">
        <div>{{ item.monthlyValue[month] }}</div>
        <div class="zz" :class="{ 'green-text': item.monthlyRates[month] > 0 }">
          <span>{{ item.monthlyRates[month] }}%</span>
          <div v-if="item.monthlyRates[month] > 0" class="green-s"></div>
          <div v-else class="gray-s"></div>
        </div>
      </td>
    </tr>
  </tbody>
</table>
th, td {
  --border-color: #dfe1e6;
  --border-width: 1px;
  padding: 4px;
  background-image: 
    linear-gradient(var(--border-color), var(--border-color)),
    linear-gradient(var(--border-color), var(--border-color)),
    linear-gradient(var(--border-color), var(--border-color)),
    linear-gradient(var(--border-color), var(--border-color));
  background-repeat: no-repeat;
  background-size: var(--border-width) 100%, 100% var(--border-width), var(--border-width) 100%, 100% var(--border-width);
  background-position: 0% 0, 100% 0, 0% 100%, 100% 100%;
}
th {
  background: #e1e3e8;
  --border-color: #fff;
}
td {
  text-align: center;
}
.sticky-column {
  position: sticky;
  left: 0;
}
.sticky-column.th-1 {
  background-color: #e1e3e8;
}

解释

  • position: sticky

    • position: sticky 是一种混合定位方式,元素在滚动时表现为 relative(相对定位),但当滚动到指定边界(如 left: 0)时,表现为 fixed(固定定位)。
    • 在这里,left: 0 表示固定列始终贴在表格的左侧。
  • 应用场景

    • 固定列常用于横向滚动的表格,确保关键列(如“人员”列)始终可见。
    • 在代码中, 和 的第一列(class="sticky-column")都被设置为固定列:

边框实现机制

边框效果通过 CSS 的 background-image 和 linear-gradient 实现,而不是传统的 border 属性。这种方法允许更灵活的边框样式(如渐变色)。 #### 详细解释

  • CSS 变量

    • --border-color: #dfe1e6:定义边框颜色(浅灰色)。
    • --border-width: 1px:定义边框宽度。
  • background-image

    • 使用四个 linear-gradient,每条渐变起点和终点颜色相同,生成纯色线:

      • 第一条:左边垂直边框。
      • 第二条:上边水平边框。
      • 第三条:右边垂直边框。
      • 第四条:下边水平边框。
  • background-size

    • var(--border-width) 100%:宽度为 1px,高度为 100%(垂直边框)。
    • 100% var(--border-width):宽度为 100%,高度为 1px(水平边框)。
  • background-position

    • 0% 0:左边垂直边框(左上角)。
    • 100% 0:上边水平边框(右上角)。
    • 0% 100%:右边垂直边框(左下角)。
    • 100% 100%:下边水平边框(右下角)。
  • background-repeat: no-repeat

    • 确保每条渐变线只绘制一次,形成边框效果。

边框效果

image.png

固定列效果

image.png