vue +js 原生实现表格拖拽改变列宽

原生js + html 实现表格拖拽列宽

可直接使用

 开发中遇到需求 表格宽度需要随着拖动改变  因为要求特殊性 所以页面没办法使用UI组件提供的 表格组件 
 只能用原生实现 
                 **好了话不多说上代码**   **可以直接使用**

Controlwidth(){
var tTD; //用来存储当前更改宽度的Table Cell,避免快速移动鼠标的问题
var table = document.getElementById(“tb_3”);
// console.log(table.rows[0].cells)

for (let j = 0; j < table.rows[0].cells.length; j++) {
    
    table.rows[0].cells[j].onmousedown = function () {
       console.log(table.rows[0].cells[j].width)

        //记录单元格
        tTD = this;
        if (event.offsetX > tTD.offsetWidth - 10) {
            tTD.mouseDown = true;
            tTD.oldX = event.x;
            tTD.oldWidth = tTD.offsetWidth;
        }
        //记录Table宽度
        //table = tTD; while (table.tagName != ‘TABLE') table = table.parentElement;
        //tTD.tableWidth = table.offsetWidth;
    };
    table.rows[0].cells[j].onmouseup = function () {
        //结束宽度调整
        if (tTD === undefined) tTD = this;
        tTD.mouseDown = false;
        tTD.style.cursor = 'default';
    };
    table.rows[0].cells[j].onmousemove = function () {
        //更改鼠标样式
        if (event.offsetX > this.offsetWidth - 10)
            this.style.cursor = 'col-resize';
        else
            this.style.cursor = 'default';
        //取出暂存的Table Cell
        if (tTD === undefined) tTD = this;
        //调整宽度
        if (tTD.mouseDown != null && tTD.mouseDown === true) {
            tTD.style.cursor = 'default';
            if (tTD.oldWidth + (event.x - tTD.oldX) > 0)
                tTD.width = tTD.oldWidth + (event.x - tTD.oldX);
            //调整列宽
            tTD.style.width = tTD.width;
            tTD.style.cursor = 'col-resize';
            //调整该列中的每个Cell
            table = tTD;
            //  console.log(tTD.width)
            while (table.tagName !== 'TABLE') table = table.parentElement;
                      //  console.log()
                  table.rows[0].cells[j].style.width = tTD.width + "px"
                  // border = "1px solid #000"
                  // console.log(table.rows[0].cells[j].style.width)
                  // console.log()
            // for (let j = 0; j < table.rows.length; j++) {
            //     //  console.log(tTD.width)
            
            // }
            //调整整个表
            //table.width = tTD.tableWidth + (tTD.offsetWidth – tTD.oldWidth);
            //table.style.width = table.width;
        }
    };
}

},

2.使用方法 本文以vue 为例 在UPdated 中引用
《vue +js 原生实现表格拖拽改变列宽》
在 table表格中 注册一个ID 这个id (用法就不说了自己悟)
《vue +js 原生实现表格拖拽改变列宽》
本文虽是转载但有部分有所改动 再此解释一下

转载文中 改变的是表格中所有列的宽度 而实际项目中多只改变当前的列宽可根据需求而定
本文只作于技术参考
转载地址如下

https://my.oschina.net/dreamHarbour/blog/882660
    原文作者:time and yang
    原文地址: https://blog.csdn.net/m0_46907690/article/details/107105408
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞