表格拖拽改变列宽

<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>
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页