原生js实现 table表格列宽拖拽


原生js实现 table表格列宽拖拽

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    function resizeTableCol(id){
            var i,
                self,
                table = document.querySelector(id),
                header = table.rows[0],
                tableX = header.clientWidth,
                length = header.cells.length;

            for (i = 0; i < length; i++) {
                header.cells[i].onmousedown = function () {
                    self = this;
                    if (event.offsetX > self.offsetWidth - 10) {
                        self.mouseDown = true;
                        self.oldX = event.x;
                        self.oldWidth = self.offsetWidth;
                    }
                };
                header.cells[i].onmousemove = function () {
                    if (event.offsetX > this.offsetWidth - 10) {
                        this.style.cursor = 'col-resize';
                    } else {
                        this.style.cursor = 'default';
                    }
                    if (self == undefined) {
                        self = this;
                    }
                    if (self.mouseDown != null && self.mouseDown == true) {
                        self.style.cursor = 'default';
                        if (self.oldWidth + (event.x - self.oldX) > 0) {
                            self.width = self.oldWidth + (event.x - self.oldX);
                        }
                        self.style.width = self.width;
                        table.style.width = tableX + (event.x - self.oldX) + 'px';
                        self.style.cursor = 'col-resize';
                    }
                };
                table.onmouseup = function () {
                    if (self == undefined) {
                        self = this;
                    }
                    self.mouseDown = false;
                    self.style.cursor = 'default';
                    tableX = header.clientWidth;
                };
            }
        }
        //使用时传入table的id名
        setTimout(resizeTableCol('#table'),300);

效果如下:
在这里插入图片描述
在这里插入图片描述