表格拖拽改变列宽

这是一个使用Vue实现的表格组件,允许用户通过拖拽表格列头的子元素来改变列宽。代码中定义了`splitDown`方法处理鼠标按下事件,计算初始位置和宽度,并在鼠标移动时实时更新列宽和整个表格的宽度。当鼠标松开时,恢复默认的鼠标样式并移除鼠标移动事件监听器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
  <div>
    <div>
      <table>
        <thead>
        <tr>
          <th v-for="item,index in heads" :id="'th_'+index" style="width:120px;">
            <div>
              {{item}}
              <sub class="split" @mousedown="splitDown($event,index)"></sub>        //sub 是鼠标拖拽的对象
            </div>
          </th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="i in 15">
          <td v-for="item in heads">
            <div style="width:100px;">
              {{item+i}}
            </div>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
  export default {
    name: "team",
    data() {
      return {
        heads: ["head1", "head2", "head3", "head4", "head5"],
      }
    },
    methods: {
      splitDown: function (e, index) {           //鼠标按下
        let left = e.target.parentNode.offsetLeft;
        let divx = e.clientX - left;
        let th_name = 'th_' + index;
        let width = $("#" + th_name).width();     //当前td的宽度
        let tabW = $("table").width();            //表格的宽度

        document.onmousemove = function (e) {    //鼠标移动
          let l = e.clientX - divx;
          document.body.style.cursor = 'col-resize';  //鼠标样式
          $("#" + th_name).width(width + l);        //td 改变宽度
          $("table").width(tabW + l);               //表格改变宽度
        };
        document.onmouseup = function (e) {       //鼠标松开
          document.body.style.cursor = 'default';   //鼠标样式
          document.onmousemove = null;
          document.onmouseup = null;
        }
      }
    }
  }
</script>

<style scoped>
  th, td {
    text-align: center;
    border: 1px solid #ddd;
    position: relative;
    height: 40px;
    width: 90px;
  }

  th div {
    padding: 8px;
    width: 100%;
    height: 100%;
  }

  .split {
    width: 5px;
    position: absolute;
    background: #ff0;
    top: 0;
    height: 40px;
    right: -2px;
    cursor: col-resize;
    z-index: 1000;
  }
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值